https://kotlinlang.org logo
Title
k

Kevin Huang

11/08/2018, 2:25 AM
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

gildor

11/08/2018, 2:25 AM
Use functions instead
or anonymous functions
not sure that it somehow similar to
goto
, it’s just return to outer scope
1
k

Kevin Huang

11/08/2018, 2:35 AM
Thank you, and like this 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

Shawn

11/08/2018, 2:59 AM
it’s really not at all similar to gotos
you can only really return forward out of a function or closure
g

gildor

11/08/2018, 3:08 AM
If you confused how return works, press Cmd+Click on it and you will jump to return point
👆 1
k

Kevin Huang

11/08/2018, 3:19 AM
Which situation we need to return forward out of a function or closure
g

gildor

11/08/2018, 3:36 AM
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

Kevin Huang

11/08/2018, 3:40 AM
❤️
I just think it's easy to make mistakes, especially when there are no labels on returns.
g

gildor

11/08/2018, 3:43 AM
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

Shawn

11/08/2018, 3:47 AM
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

Kevin Huang

11/08/2018, 3:52 AM
I got it, the
return
in closure is not for closure , it's for the outer function. Is it right?
g

gildor

11/08/2018, 3:55 AM
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

Kevin Huang

11/08/2018, 3:56 AM
I see. Thank you all.