Yudhistira Arya
Yudhistira Arya

Reputation: 3671

Kotlin anonymous function use case?

Based on my understanding, anonymous function in Kotlin allow you to specify return type. In addition to that, return statement inside anonymous will exit only the function block, while in lambda it will exit the enclosing function.

Still, I can't imagine what would be the real world use case of anonymous function in Kotlin that lambda syntax cannot provide?

Kotlin Higher Order Function and Lambda

Upvotes: 5

Views: 2339

Answers (2)

John
John

Reputation: 1314

The use case is that sometimes we may wish to be explicit about the return type. In those cases, we can use so called an anonymous function. Example:

fun(a: String, b: String): String = a + b

Or better return control like:

fun(): Int {
    try {
        // some code
        return result
    } catch (e: SomeException) {
        // handler
        return badResult
        }
}

Upvotes: 6

voddan
voddan

Reputation: 33769

Anonymous functions (a.k.a function expressions) are very handy when you have to pass a huge lambda with complex logic and want early returns to work. For example if you write a dispatcher in spark-java:

get("/", fun(request, response) {
    // Your web page here
    // You can use `return` to interrupt the handler 
})

Upvotes: 2

Related Questions