Avatar ·

What does `return@` mean in Kotlin and how to properly use return labels?

Hi everyone! I'm learning Kotlin and came across a strange construct `return@`. I see it in code with RxJava, but I don't understand why it's needed.\n\nI have this code:\n\n```kotlin\nfun main() {\n listOf(1, 2, 3, 4, 5).forEach {\n if (it == 3) {\n return@forEach\n }\n println(it)\n }\n println("Done")\n}\n```\n\nI expected that `return` would simply exit the forEach, but it exits the entire main function. Without `@forEach`, the code doesn't even compile with the error "return is not allowed here". Why is that?\n\nI also saw this example with RxJava:\n\n```kotlin\nobservable.subscribe { value ->\n if (value.isInvalid()) {\n return@subscribe\n }\n process(value)\n}\n```\n\nWhat does `return@subscribe` mean? Why can't you just write `return`? Please explain.