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