코틀린은 세가지 jump expression 을 가진다.
returnby default returns from the nearest enclosing function or anonymous function.
breakterminates the nearest enclosing loop.
continueproceeds to the next step of the nearest enclosing loop.
세가지 expression 은 모두 더 큰 expression의 일부분으로서 사용될 수 있다.
val s = person.name ?: return //엘비스 연산자
타입은 Nothing 타입!
Break and continue labels
코틀린의 모든 표현식은 label 로 마킹될 수 있음 e.g.)
abc@, fooBar@loop@ for (i in 1..100) { // ... }
for loop의 label (
loop@)을 통해 break 혹은 continue의 대상을 명확히 표시 할 수 있다.loop@ for (i in 1..100) { for (j in 1..100) { if (...) break@loop } }
Return to labels
코틀린에서 함수는 (function literals, local functions 와 object expressions)를 통해 중첩 될 수 있습니다.
중첩 함수 구조에서 Qualified
return을 통해 바깥 함수로 리턴 할 수 있습니다.가장 중요한 use case 는 람다 표현식입니다.
아래같이 쓰면 람다 표현식은 가장 가까운 enclosing 함수인
foo 로 리턴합니다.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") }
람다식에서 qualified
returnfun foo() { listOf(1, 2, 3, 4, 5).forEach lit@{ if (it == 3) return@lit // local return to the caller of the lambda - the forEach loop print(it) } print(" done with explicit label") }
fun foo() { listOf(1, 2, 3, 4, 5).forEach { if (it == 3) return@forEach // local return to the caller of the lambda - the forEach loop print(it) } print(" done with implicit label") }
대안으로 람다식을 안쓰고 익명 함수를 쓰면 리턴문은 익명 함수로 리턴합니다.
fun foo() { listOf(1, 2, 3, 4, 5).forEach(fun(value: Int) { if (value == 3) return // local return to the caller of the anonymous function - the forEach loop print(value) }) print(" done with anonymous function") }