Ranges represent a sequence of values that you can iterate over. They are often used in loops and condition checks.
Use start..end to define a range. It includes both endpoints.
fun main() {
val range = 1..5
for (i in range) {
print("$i ")
}
}
Output: 1 2 3 4 5
downToTo count in reverse order, use downTo.
fun main() {
for (i in 5 downTo 1) {
print("$i ")
}
}
Output: 5 4 3 2 1
stepYou can skip values by adding step after the range.
fun main() {
for (i in 1..10 step 2) {
print("$i ")
}
}
Output: 1 3 5 7 9
Use in or !in to test if a value exists in a range.
fun main() {
val x = 7
if (x in 1..10) {
println("$x is in the range")
}
}
x to 15 and see how the condition fails!
Ranges aren't limited to numbers โ you can create ranges of characters too.
fun main() {
for (ch in 'A'..'F') {
print("$ch ")
}
}
Output: A B C D E F
a..b โ from a to bb downTo a โ reversestep โ skip stepsin โ check existencewhen expressions!
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!