How to create a class that takes function as a constructor argument. Then, use this function at some later point in the class.
3 Answers
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:
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):
val a = A { println("this is the lambda") }
Comments
A real world example can be observed in SynchronizedLazyImpl, the class backing lazy delegates.
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.