Programming/Kotlin

Kotlin Loop

Albothyl 2022. 4. 23. 11:48

for

for (item in collection) print(item)

for (item: Int in ints) {
    // ...
}

for (i in 1..3) {
    println(i)
}

for (i in 6 downTo 0 step 2) {
    println(i)
}

for (i in array.indices) {
    println(array[i])
}

for ((index, value) in array.withIndex()) {
    println("the element at $index is $value")
}

 

while

 

while (x > 0) {
    x--
}

do {
    val y = retrieveData()
} while (y != null) // y is visible here!

 

Returns and jumps

//return by default returns from the nearest enclosing function or anonymous function.
val s = person.name ?: return

//break terminates the nearest enclosing loop.
//continue proceeds to the next step of the nearest enclosing loop.
loop@ for (i in 1..100) {
    for (j in 1..100) {
        if (...) break@loop
        if (...) continue@loop
    }
}

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

//명시적
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")
}

// 암시적
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")
}

// anonymous function
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")
}