Search code examples
kotlinkotlin-extension

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?


Solution

  • 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()