kotlin loop for code example
Example 1: for loop kotlin
val array = arrayOf(1, 3, 9)
for (item in array) {
//loops items
}
for (index in 0..array.size - 1) {
//loops all indices
}
for (index in 0 untill array.size) {
//loops all indices
}
for (index in array.indices) {
//loops all indices (performs just as well as two examples above)
}
Example 2: Kotlin when
val x = 3
when(x) {
3 -> println("yes")
8 -> println("no")
else -> println("maybe")
}
// when can also be used as an expression!
val y = when(x) {
3 -> "yes"
8 -> "no"
else -> "maybe"
}
println(y) // "yes"
Example 3: kotlin loop
val school = arrayOf("shark", "salmon", "minnow")
for (element in school) {
print(element + " ")
}
-> shark salmon minnow
for ((index, element) in school.withIndex()) {
println("Item at $index is $element\n")
}
-> Item at 0 is shark
Item at 1 is salmon
Item at 2 is minnow