在Kotlin中传递和使用函数作为构造函数参数

n.a*_*001 6 android kotlin

如何创建一个将函数作为构造函数参数的类.然后,在课程的稍后部分使用此功能.

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)