2

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?

piotrek
  • 13,982
  • 13
  • 79
  • 165
  • you can't instantiate abstract classes :p – Willi Mentzel Dec 29 '18 at 23:48
  • 1
    Note: just because you can do this (as per Sergey's answer), doesn't mean it's a good idea. For one thing, it's likely to confuse most people who read your code; and (as per the issue with semicolons that Sergey mentioned) it's likely to have some unexpected effects. – gidds Dec 30 '18 at 00:12

1 Answers1

4

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()
Sergio
  • 27,326
  • 8
  • 128
  • 149