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

时间:2017-07-04 19:14:12

标签: android kotlin

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

3 个答案:

答案 0 :(得分:10)

您可以拥有一个具有函数类型的属性,就像使用任何其他类型一样:

class A(val f: () -> Unit) {

    fun foo() {
        f()
    }

}

从这里,您可以将该函数作为方法引用传递给构造函数:

fun bar() {
    println("this is bar")
}

val a = A(::bar)
a.foo()             // this is bar

或作为一个lambda:

val a = A({ println("this is the lambda") })

你甚至可以为lambda作为函数的最后一个参数执行通常的语法糖(虽然这有点疯狂):

val a = A { println("this is the lambda") }

答案 1 :(得分:1)

void clear() { QLayoutItem *child; while ((child = m_formLayout->takeAt(0)) != 0) { QLayout * layout = child->layout(); QSpacerItem * spacer = child->spacerItem(); QWidget * widget = child->widget(); if(layout && !doesOwnObject(layout)) delete layout; if(spacer && !doesOwnObject(spacer)) delete spacer; if(widget) { if(doesOwnObject(widget)) widget->setParent(0L); else delete widget; } } } ,支持SynchronizedLazyImpl代表的班级中可以观察到一个真实世界的例子。

lazy

当我们使用public fun <T> lazy(lock: Any?, initializer: () -> T): Lazy<T> = SynchronizedLazyImpl(initializer, lock) 时,作为lambda传递的val x by lazy {...}实际上存储为initializer实例中的属性,并在相应的SynchronizedLazyImpl后调用正在第一次访问。

答案 2 :(得分:0)

如果您有多个构造函数声明,则可以使用此

...

private var listener : (() -> Unit)? = null

constructor(context: Context, listener: (() -> Unit)?) : this(context){
        this.listener = listener
}

constructor(context: Context) : super(context, attrs = null)

...