Kotlin anonymous function use case?

2019-06-28 04:34发布

问题:

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

回答1:

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
        }
}


回答2:

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 
})


标签: kotlin