Hanbit the Developer

Kotlin Documentation | Control flow 본문

Mobile/Kotlin

Kotlin Documentation | Control flow

hanbikan 2023. 5. 22. 14:20

Kotlin Documentation 시리즈에 대해

Category: Concepts

문서 링크: https://kotlinlang.org/docs/control-flow.html


Returns and jumps

Break and continue labels

loop@ for (i in 1..100) {
    for (j in 1..100) {
        if (...) break@loop
    }
}
fun 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")
}

// or

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")
}

// or

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")
}

Exceptions

  • 코틀린에서 모든 exception 클래스는 Throwable을 상속한다.

Throw and Catch

throw Exception("Hi There!")
try {
    // some code
} catch (e: SomeException) {
    // handler
} finally {
    // optional finally block
}

Try is an expression

val a: Int? = try { input.toInt() } catch (e: NumberFormatException) { null }

There is no checked exceptions in kotlin.