BeginnerLesson 4 of 16
Loops & Ranges – Kotlin
for over ranges and collections, while, and breaking out with labels.
The for loop runs over anything that provides elements – usually a range or a collection. 1..3 includes the end, 0 until 3 (or 0..<3) excludes it.
for (i in 1..3) println("Round $i") // 1 2 3
for (i in 0 until 3) print("$i ") // 0 1 2
println()
for (i in 10 downTo 1 step 3) print("$i ") // 10 7 4 1
println()
for ((index, frucht) in listOf("Apple", "Pear").withIndex()) {
println("$index: $frucht")
}
repeat(2) { println("Hello") }while and do-while work as in other languages. break exits, continue skips. With a label, you can also break out of outer loops.
var n = 0
while (true) {
n++
if (n % 2 == 0) continue
if (n > 7) break
print("$n ") // 1 3 5 7
}
println()
aussen@ for (i in 1..3) {
for (j in 1..3) {
if (i * j == 4) break@aussen
print("$i$j ") // 11 12 13 21
}
}TipRanges are objects too:
(1..5).sum() gives 15, 'a'..'e' is a character range, and 5 in 1..10 checks membership.Warning
1..0 is an empty range – the loop does not run. To count backwards you need downTo.