16

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 3

24

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") }
Sign up to request clarification or add additional context in comments.

Comments

2

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)

...

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.