1

Where does one use Kotlin anonymous functions defined using the fun keyword? Below is an example taken from their documentation. How would one go about invoking this or passing this into function / object, etc.

fun(s: String): Int { return s.toIntOrNull() ?: 0 }

2 Answers 2

3

Anonymous functions provide an alternate syntax to pass a lambda, so both the following lines produce identical result

intList.filter(fun(item: Int): Boolean { return item > 0 })
intList.filter{ it > 0 }

Advantage of using anonymous function is local return statements


to demonstrate this, Lets consider a trivial lambda which contains multiple return statements

strList.forEachIndexed { index, s ->
    when(index){
         0 -> return@forEachIndexed 
         1 -> return@forEachIndexed
         3 -> return@forEachIndexed
         else -> { Log.d("TAG", "$index -> $s")}
     }
}

here if we used return instead of return@forEachIndexed, that would return us from the outer scope. to return from lambda, we need to specify the label.

If however the lambda contains multiple return@forEachIndexed statements then this syntax becomes very redundant and verbose, it would be nice if we could use simple return without that label. this is where anonymous functions come in.

using anonymous function above code can be written as

strList.forEachIndexed(fun (index, string) {
    when(index){
         0 -> return  // No need to specify label, this returns from anon function not from outer scope
         1 -> return
         3 -> return
         else -> { Log.d("TAG", "$index -> $string")}
     }
})
Sign up to request clarification or add additional context in comments.

Comments

2

From the same documentation:

The parameters and the return type are specified in the same way as for regular functions, except the parameter types can be omitted if they can be inferred from the context:

ints.filter(fun(item) = item > 0)

In practice:

fun main() {
    val ints = listOf(-2, -1, 0, 1, 2)

    // As in your snippet
    println(ints.filter(fun(item: Int): Boolean { return item > 0 }))
    // Outputs [1, 2]

    // Or simply
    println(ints.filter(fun(item) = item > 0))
    // Outputs [1, 2]
}

4 Comments

thanks @enzo. Is there an advantage in using fun in these use cases vs. using a lambda? 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. From the same link I've sent: "The lambda expression syntax (...) is missing one thing – the ability to specify the function’s return type. In most cases, this is unnecessary because the return type can be inferred automatically. However, if you do need to specify it explicitly, you can use an alternative syntax: an anonymous function."
Using an anonymous fun is very rare in my experience; as enzo says, a lambda works (and is simpler) in nearly all cases.  But it's good to be aware, just in case.
@enzo actual use case for anonymous function is to get rid of labeled returns in a lambda

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.