https://kotlinlang.org logo
Title
a

Ayden

08/30/2018, 6:28 AM
@diesieben07 can I consider this syntax
->
in lamdas as return?
d

diesieben07

08/30/2018, 6:29 AM
Not quite. The return value of a lambda is usually it's last expression: https://kotlinlang.org/docs/reference/lambdas.html#returning-a-value-from-a-lambda-expression
a

Ayden

08/30/2018, 7:00 AM
What does the
@lit
use for?
There is another annotation like
@filter
e

edwardwongtl

08/30/2018, 7:02 AM
Usually
return@filter
, making a return to another scope
a simple
return
will only return from the current function scope.
a

Ayden

08/30/2018, 7:06 AM
@edwardwongtl where can I find those annotation documentation?
e

edwardwongtl

08/30/2018, 7:07 AM
That’s not quite a annotation, search for
Non-local return
a

Ayden

08/30/2018, 7:30 AM
@edwardwongtl non-local return is useful if you still want to process something after return is it?
e

edwardwongtl

08/30/2018, 7:32 AM
It is useful when you are nesting too much lambdas
a

Ayden

08/30/2018, 7:40 AM
I have an issue here. How come these two produce different outcomes?
fun foo() {
    run loop@{
        listOf(1, 2, 3, 4, 5).forEach {
            if (it == 3) return@loop // non-local return from the lambda passed to run
            print(it)
        }
    }
    print(" done with nested loop")
}
12 done with nested loop
fun foo() {
    run {
        listOf(1, 2, 3, 4, 5).forEach {
            if (it == 3) return@forEach
            // non-local return from the lambda passed to run
            print(it)
        }
    }
    print(" done with nested loop")
}
1245 done with nested loop
I read the previous example, actually this two can produce the same value.
e

edwardwongtl

08/30/2018, 7:43 AM
return@forEach
actually work as
continue
a

Ayden

08/30/2018, 8:46 AM
@edwardwongtl This line of code is similar like
continue
or
return@forEach
right?
fun foo() {
    listOf(1, 2, 3, 4, 5).forEach lit@{
        if (it == 3) return@lit // local return to the caller of the lambda, i.e. the forEach loop
        print(it)
    }
    print(" done with explicit label")
}

fun main(args: Array<String>) {
    foo()
}
:yes: 1
fun foo() {
    run loop@{
        listOf(1, 2, 3, 4, 5).forEach {
            if (it == 3) return@loop // non-local return from the lambda passed to run
            print(it)
        }
    } <- Here is the end of the local scope right?
    print(" done with nested loop")
}
This is the last example of the non-local return.
The reason why the result terminal at
12 done with nested loop
is because the end of the local scope is after the close bracket of the
run
.
Am I right?
s

Shawn

08/30/2018, 1:32 PM
You might want the docs for labels and using return with them https://kotlinlang.org/docs/reference/returns.html