For Loop and Ranges


For Loop:

Often when you work with arrays, you need to loop through all of the elements.

To loop through array elements, use the for loop together with the in operator:

fun main() {
val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
for (x in cars) {
println(x)
}
}
Output:
Volvo
BMW
Ford
Mazda

Traditional For Loop:

Unlike Java and other programming languages, there is no traditional for loop in Kotlin.

In Kotlin, the for loop is used to loop through arrays, ranges, and other things that contain a countable number of values.


Kotlin Ranges :

With the for loop, you can also create ranges of values with "..":

fun main() {
for (nums in 5..15) {
println(nums)
}
}
Output:
5
6
7
8
9
10
11
12
13
14
15

Check if a Value Exists

You can also use the in operator to check if a value exists in a range:

val cars = arrayOf("Volvo", "BMW", "Ford", "Mazda")
if ("Volvo" in cars) {
println("It exists!")
} else {
println("It does not exist.")
}

Break or Continue a Range

You can also use the break and continue keywords in a range/for loop:

Skip the value of 10 in the loop, and continue with the next iteration:

for (nums in 5..15) {
if (nums == 10) {
continue
}
println(nums)
}

..

Comments