[英]Passing and using function as constructor argument in Kotlin
How to create a class that takes function as a constructor argument. 如何创建一个将函数作为构造函数参数的类。 Then, use this function at some later point in the class.
然后,在课程的稍后部分使用此功能。
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()
}
}
From here, you can pass that function to the constructor as a method reference: 从这里,您可以将该函数作为方法引用传递给构造函数:
fun bar() {
println("this is bar")
}
val a = A(::bar)
a.foo() // this is bar
Or as a lambda: 或者作为一个lambda:
val a = A({ println("this is the lambda") })
And you can even do the usual syntactic sugar for lambdas that are the last parameter of a function (although this is getting a little wild): 你甚至可以为lambda作为函数的最后一个参数做常用的语法糖(虽然这有点疯狂):
val a = A { println("this is the lambda") }
A real world example can be observed in SynchronizedLazyImpl
, the class backing lazy
delegates. 在
SynchronizedLazyImpl
可以观察到一个真实的例子,这是支持lazy
委托的类。
public fun <T> lazy(lock: Any?, initializer: () -> T): Lazy<T> =
SynchronizedLazyImpl(initializer, lock)
When we use val x by lazy {...}
, the initializer
, passed as a lambda, is actually stored as a property in an instance of SynchronizedLazyImpl
and called later when the corresponding val x
is being accessed for the first time. 当我们
val x by lazy {...}
使用val x by lazy {...}
,作为lambda传递的initializer
实际上作为属性存储在SynchronizedLazyImpl
的实例中,并且在第一次访问相应的val x
时稍后调用。
If you have more than one constructor declarations you can use this 如果您有多个构造函数声明,则可以使用它
...
private var listener : (() -> Unit)? = null
constructor(context: Context, listener: (() -> Unit)?) : this(context){
this.listener = listener
}
constructor(context: Context) : super(context, attrs = null)
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.