Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin anonymous function use case?

Tags:

kotlin

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

like image 719
Yudhistira Arya Avatar asked Apr 02 '17 08:04

Yudhistira Arya


People also ask

Why do we use anonymous functions in Kotlin?

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:

What is a functional type in Kotlin?

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:

How to declare return types in Lambdas in Kotlin?

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.

Is there a use case for an anonymous function definition?

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.


2 Answers

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
        }
}
like image 144
John Avatar answered Oct 23 '22 01:10

John


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 
})
like image 2
voddan Avatar answered Oct 23 '22 01:10

voddan