skip to content
Posts · November 2018

Kotlin functions


  • 1、function member
val onClick: () -> Unit =
  • 2、nullable function
val intFunc: ((Int, Int) -> Int)? = null
  • 3、function type
typealias ClickHandler = (Button, ClickEvent) -> Unit
  • 4、anonymous function
fun(s: String): Int { return s.toIntOrNull() ?: 0 }
  • 5、lamda expression
val reminderFunc = { index: Int -> index % 2 }
  • 6、callable reference
member function ::toString, String::toInt
member property List::size
constructor ::someConstructorFuncName
  • 7、class function
class IntTransformer: (Int) -> Int {
override operator fun invoke(x: Int): Int = TODO()
}
val intFunction: (Int) -> Int = IntTransformer()
  • 8、instance function
val repeatFun: String.(Int) -> String = { times ->
this.repeat(times)
}
val twoParameters: (String, Int) -> String = repeatFun
val s1 = repeatFun(“str”, 2)
val s2 = “str”.repeatFun(2)
  • 9、builder function
class HTML {
fun body() { … }
}
fun html(init: HTML.() -> Unit): HTML {
val html = HTML() // create the receiver object
html.init() // pass the receiver object to the lambda
return html
}
val obj = html { // lambda with receiver begins here
body() // calling a method on the receiver object
}
  • 10、infix function
class HTML {
infix fun escape(escaper: (String) -> String){…}
}
val obj = HTML() escape { s: String -> “switch s case xxx”}