Ranges
There is a set of tools for defining ranges in Kotlin. Let's have a brief look at them.
fun main() {
for(i in 0..3) { // 1
print(i)
}
print(" ")
for(i in 0 until 3) { // 2
print(i)
}
print(" ")
for(i in 2..8 step 2) { // 3
print(i)
}
print(" ")
for (i in 3 downTo 0) { // 4
print(i)
}
print(" ")
}
- Iterates over a range starting from 0 up to 3 (inclusive). Like 'for(i=0; i<=3; ++i)' in other programming languages (C/C++/Java).
- Iterates over a range starting from 0 up to 3 (exclusive). Like for loop in Python or like 'for(i=0; i<3; ++i)' in other programming languages (C/C++/Java).
- Iterates over a range with a custom increment step for consecutive elements.
- Iterates over a range in reverse order.
Char ranges are also supported:
fun main() {
for (c in 'a'..'d') { // 1
print(c)
}
print(" ")
for (c in 'z' downTo 's' step 2) { // 2
print(c)
}
print(" ")
}
- Iterates over a char range in alphabetical order.
- Char ranges support
step
anddownTo
as well.
Ranges are also useful in if
statements:
fun main() {
val x = 2
if (x in 1..5) { // 1
print("x is in range from 1 to 5")
}
println()
if (x !in 6..10) { // 2
print("x is not in range from 6 to 10")
}
}
- Checks if a value is in the range.
!in
is the opposite ofin
.