Use case for Kotlin anonymous function?

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

However, I can't imagine what a real-life use case for an anonymous function would be in Kotlin that the lambda syntax cannot provide?

Kotlin higher order function and lambda

+3


source to share


2 answers


The use case is that sometimes we can be explicit about the return type. In such cases, we can use a so-called anonymous function. Example:

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

      



Or is it better to return control, for example:

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

      

+3


source


Anonymous functions (aka function expressions) come in very handy when you need to pass in a huge lambda with complex logic and want early results to be returned. 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 
})

      

+1


source







All Articles