can someone explain or point documentation what is...
# getting-started
j
can someone explain or point documentation what is the reasoning behind that using return in list.map { return xxx } is not actually return of value of the lambda function? and what is the use case where this return behavior would be useful?
e
You mean the
return
in
map
actually returns to a outer scope?
j
Yes, "non-local returns" it is
e
The reasoning is in consistency. In Kotlin,
return
is consistent in that it returns from the enclosing
fun
by default. From lambdas you don’t usually return — you program them (usually) in functional style where their value is the last expression.
j
I made a silly bug because I tried to write
Copy code
list.map { it -> 
    return if (condition) {
        Foo()
    } else Bar()
}
which of course did not work, so I quickly changed it to
Copy code
list.map { it ->
    if (condition) { 
        Foo()
    } 
    Bar()
}
which I then found out should be
Copy code
list.map { it ->
    if (condition) {
        Foo()
    } else {
        Bar()   
    }
}
e
It makes sense to add some kind of inspection that would recognize mistake of the first type. It should be easy to detect.
j
Agreed