Ranges in Kotlin provide a concise way to express sequences of values. They are particularly useful for iterating over a progression of numbers or characters.
Kotlin ranges are created using the .. operator or the rangeTo() function. Here's the basic syntax:
val numberRange = 1..10
val charRange = 'a'..'z'
Kotlin supports several types of ranges:
Ranges are commonly used in Kotlin For Loops to iterate over a sequence of values:
for (i in 1..5) {
println(i)
}
// Output: 1 2 3 4 5
To create a reverse range, use the downTo function:
for (i in 5 downTo 1) {
println(i)
}
// Output: 5 4 3 2 1
You can specify a step for your range using the step function:
for (i in 1..10 step 2) {
println(i)
}
// Output: 1 3 5 7 9
Ranges can be used in conditional statements to check if a value is within a specific range:
val x = 15
if (x in 1..20) {
println("x is in the range")
}
// Output: x is in the range
To create a range that excludes its upper bound, use the until function:
for (i in 1 until 5) {
println(i)
}
// Output: 1 2 3 4
Kotlin ranges offer a versatile and expressive way to work with sequences of values. They simplify iteration, improve code readability, and integrate seamlessly with other Kotlin features. By mastering ranges, you'll write more concise and efficient Kotlin code.