You can have a property with a function type just like you would with any other type:
class A(val f: () -> Unit) {
fun foo() {
f()
}
}
在这里,您可以将该函数作为方法引用传递给构造函数:
fun bar() {
println("this is bar")
}
val a = A(::bar)
a.foo() // this is bar
Or as a lambda:
val a = A({ println("this is the lambda") })
你甚至可以为lambda做通常的语法分析,lambda是函数的最后一个参数(尽管这有点疯狂):
val a = A { println("this is the lambda") }