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
Although the return type is inferred automatically by the Kotlin compiler in most cases, for cases where it cannot be inferred on its own or it needs to be declared explicitly, we use the anonymous functions. In this article, we will see how to use anonymous functions. Before that we have some:
Function type declaration The Kotlin language allows you to declare the type of anonymous functions or lambda expressions. Such a type is called a function type. The functional type allows you to extend the use of lambda expressions. The function type defines the characteristic features of the lambda expression, namely:
In Kotlin, we can have functions as expressions by creating lambdas. Lambdas are function literals that is, they are not declared as they are expressions and can be passed as parameters. However, we cannot declare return types in lambdas.
Presumably there is no use case then of standalone anonymous function definitions (i.e. where a lambda is not feasible). In fact there's a use case, but it's not common.
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
}
}
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
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With