kotlinfunctional-programmingkotlin-coroutines

What is it called and what does it mean when a function "equals" another function and provides a body?


Like in this expression:

fun main() = runBlocking { ... }

Are we executing the runBlocking function and passing the { } body in as a functional argument?

What is this called?

I know it immediately executes main because of the parens.


Solution

  • This is not a single language feature.

    First, you are allowed to use a single expression as the function's body, to replace that function's return value. This is called a single-expression function. For example, the following declarations of f are equivalent:

    fun f(): Int {
        return 0
    }
    
    fun f() = 0
    

    Second, when a function takes a function type as its last parameter, you can pass a lambda expression to that parameter after the ) of the call:

    fun iTakeAFunction(x: Int, f: () -> Unit) { }
    
    // the following are equivalent
    iTakeAFunction(0, { println("Hello World") })
    iTakeAFunction(0) { println("Hello World") }
    

    This syntax is called trailing lambda.

    When the lambda expression is the only parameter that you are passing, you can even omit the ():

    fun iTakeAFunction(f: () -> Unit) { }
    
    // the following are equivalent
    iTakeAFunction({ println("Hello World") })
    iTakeAFunction() { println("Hello World") }
    iTakeAFunction { println("Hello World") }
    

    runBlocking is a function like this, so the code in the question desugars to:

    fun main(): Unit {
        return runBlocking({ ... })
    }
    

    In other words, main simply calls runBlocking with a lambda expression as its parameter.