Do you like "Return at Labels" ? Specially in lamb...
# announcements
k
Do you like "Return at Labels" ? Specially in lambdas. It is too similar to
goto
. And in lambdas,can't call "return" directly. In some complex cases , can't return a value immediately , need some ugly code to solve. Any suggests for this situation? Thanks.
g
Use functions instead
or anonymous functions
not sure that it somehow similar to
goto
, it’s just return to outer scope
1
k
Thank you, and like this code:
Copy code
fun foo() {
    listOf(1, 2, 3, 4, 5).forEach {
        if (it == 3) return // non-local return directly to the caller of foo()
        print(it)
    }
    println("this point is unreachable")
}
It may make me understand the wrong logic. At the beginning i thing the "return" just break the
forEach
but not return directly to the caller of foo().
s
it’s really not at all similar to gotos
you can only really return forward out of a function or closure
g
If you confused how return works, press Cmd+Click on it and you will jump to return point
👆 1
k
Which situation we need to return forward out of a function or closure
g
there are a lot of cases when you want to have early return from block
But in general yes, I usually try to avoid such cases when it’s possible
one way is just extract some code to another function, it also improves readability
k
❤️
I just think it's easy to make mistakes, especially when there are no labels on returns.
g
If you don’t know how
return
work yes, it can be not obvious
but it allows to write much mire complex lambdas and use early return (good for nullability)
s
I feel like it’s much more intuitive that a return in a trailing closure returns from the outer function than to worry about it just returning out of the closure and having to deal with things in the rest of the function - it acts more like a regular for loop in that regard
return at labels just lets you opt into returning to the closure call and explicitly handling whatever state your function is in at that point
k
I got it, the
return
in closure is not for closure , it's for the outer function. Is it right?
g
correct, return without label always returns from outer function
but don’t forget that you also can have anonymous functions where return also works
See documentation, it covers those topics https://kotlinlang.org/docs/reference/returns.html
👏 2
k
I see. Thank you all.