piotrek
piotrek

Reputation: 14520

Does Kotlin permit extension methods on lambdas?

I'm trying to make a nice SAM-like API for instantiating abstract classes because I don't like object expressions. I'm trying to do something like:

{my lambda code here}.my_extension_function()

Is this possible with Kotlin?

Upvotes: 2

Views: 390

Answers (1)

Sergio
Sergio

Reputation: 30595

Yes it is possible. The sample code is:

// extension function on lambda with generic parameter
fun <T> ((T) -> Unit).my_extension_function() {
    // ...
}

// extension function on lambda without generic parameter
fun (() -> Unit).my_extension_function() {
    // ...
}

And use it, for example, like this:

// lambda variable with generic parameter
val lambda: (Int) -> Unit = {
    // 'it' contains Int value
    //...
}

// lambda variable without generic parameter
val lambda: () -> Unit = {
    //...
}

lambda.my_extension_function()

// also we can call extension function on lambda without generic parameter like this
{
    //...
}.my_extension_function()

// or with generic parameter
{ i: Int ->
        //...
}.my_extension_function()

Note: if you call extension function on lambda without creating a variable and there is a function call before it you need to add semicolon after function call, e.g.:

someFunction();

{
    //...
}.my_extension_function()

Upvotes: 4

Related Questions