https://kotlinlang.org logo
Title
j

Jukka Siivonen

11/13/2018, 7:59 AM
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

edwardwongtl

11/13/2018, 8:13 AM
You mean the
return
in
map
actually returns to a outer scope?
j

Jukka Siivonen

11/13/2018, 9:17 AM
Yes, "non-local returns" it is
e

elizarov

11/13/2018, 10:06 AM
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

Jukka Siivonen

11/13/2018, 11:23 AM
I made a silly bug because I tried to write
list.map { it -> 
    return if (condition) {
        Foo()
    } else Bar()
}
which of course did not work, so I quickly changed it to
list.map { it ->
    if (condition) { 
        Foo()
    } 
    Bar()
}
which I then found out should be
list.map { it ->
    if (condition) {
        Foo()
    } else {
        Bar()   
    }
}
e

elizarov

11/13/2018, 1:49 PM
It makes sense to add some kind of inspection that would recognize mistake of the first type. It should be easy to detect.
j

Jukka Siivonen

11/13/2018, 3:38 PM
Agreed