zsm*_*b13 10
您可以拥有一个具有函数类型的属性,就像使用任何其他类型一样:
class A(val f: () -> Unit) {
fun foo() {
f()
}
}
Run Code Online (Sandbox Code Playgroud)
从这里,您可以将该函数作为方法引用传递给构造函数:
fun bar() {
println("this is bar")
}
val a = A(::bar)
a.foo() // this is bar
Run Code Online (Sandbox Code Playgroud)
或者作为一个lambda:
val a = A({ println("this is the lambda") })
Run Code Online (Sandbox Code Playgroud)
你甚至可以为lambda作为函数的最后一个参数做常用的语法糖(虽然这有点疯狂):
val a = A { println("this is the lambda") }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3875 次 |
| 最近记录: |