Kotlin functions
  • 1、function member
1
val onClick: () -> Unit = …
  • 2、nullable function
1
val intFunc: ((Int, Int) -> Int)? = null
  • 3、function type
1
typealias ClickHandler = (Button, ClickEvent) -> Unit
  • 4、anonymous function
1
fun(s: String): Int { return s.toIntOrNull() ?: 0 }
  • 5、lamda expression
1
val reminderFunc = { index: Int -> index % 2 }
  • 6、callable reference
1
2
3
member function ::toString, String::toInt
member property List::size
constructor ::someConstructorFuncName
  • 7、class function
1
2
3
4
class IntTransformer: (Int) -> Int {
override operator fun invoke(x: Int): Int = TODO()
}
val intFunction: (Int) -> Int = IntTransformer()
  • 8、instance function
1
2
3
4
5
6
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
1
2
3
4
5
6
7
8
9
10
11
12
13
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
1
2
3
4
class HTML {
infix fun escape(escaper: (String) -> String){…}
}
val obj = HTML() escape { s: String -> “switch s case xxx”}
adb snapshot
IDEA Jetty
© 2020 qomg
Powered by hexo | Theme is blank