Shamil
Shamil

Reputation: 61

Kotlin labmda invoke alternatve

Assume we have the following code:

fun interface A {
    fun a()
}

interface B {
    fun b(a: A)
}

fun x(callback: A.() -> Unit) = object : B {
    override fun b(a: A) {
        a.callback()
        //callback.invoke(a)
    }
}

Why we can use a.callback() instead of callback.invoke(a) What is the meaning of such a syntax? Can't find it in official documentation. And yes, here a.callback() is also equivalent to (a as A).callback()

Upvotes: 1

Views: 46

Answers (1)

Sweeper
Sweeper

Reputation: 274235

The type of callback is a function type with a receiver. From the documentation:

Function types can optionally have an additional receiver type, which is specified before the dot in the notation: the type A.(B) -> C represents functions that can be called on a receiver object A with a parameter B and return a value C.

callback is of type A.() -> Unit, so it can be called on an instance of A (i.e. the parameter a).

This is similar to how you normally call extension functions. callback here acts like an extension function on A (because its type is A.() -> Unit), so you can call it like an extension function inside x.

Upvotes: 2

Related Questions