Kotlin offers powerful tools to work with ranges of values, making it easy to iterate through sequences of numbers, characters, or other ordered types. Range and progression operators allow you to define a start and an end point and automatically handle the steps between them. These features are especially useful when looping through a sequence or when you need to check if a value falls within a specific range.
In this article, we’ll explore Kotlin’s range and progression operators, how they work, and when to use them. You’ll also learn practical examples of how to leverage ranges in loops, conditions, and iterations.
What Are Range and Progression Operators?
In Kotlin, a range represents a set of values between a defined starting point and an ending point. A progression represents a sequence of values that progresses from a start to an end value, with an optional step. Ranges and progressions are particularly helpful when you want to iterate over a set of consecutive values, check if a value lies within a range, or generate sequences of values.
Kotlin supports several types of ranges and progressions, including:
- Integer ranges (
1..10
) - Character ranges (
'a'..'z'
) - Reverse ranges (
10 downTo 1
) - Step progression (
1..10 step 2
)
Let’s dive into each of these with examples.
1. Creating a Range
You can create a range in Kotlin using the range operator (..
). This operator defines a range that starts at the left operand and ends at the right operand, inclusive of both bounds.
Example:
fun main() {
val range = 1..5
println(range) // Output: 1..5
}
In this example, the range consists of numbers from 1
to 5
, inclusive.
2. Iterating Over a Range with for
Loops
Ranges are commonly used in for
loops to iterate over a sequence of values. This is a concise way to handle loops where you know the start and end values.
Example:
fun main() {
for (i in 1..5) {
println(i)
}
}
Output:
1
2
3
4
5
Here, the loop iterates over the range from 1
to 5
, printing each number.
3. Reverse Ranges: downTo
The downTo
function creates a range in reverse order, starting from the higher value and progressing down to the lower value.
Example:
fun main() {
for (i in 5 downTo 1) {
println(i)
}
}
Output:
5
4
3
2
1
This loop iterates from 5
down to 1
, in reverse order.
4. Step Progressions: step
The step
function allows you to define the step size when iterating over a range. By default, ranges increment by 1
, but you can specify a different step size to skip values.
Example:
fun main() {
for (i in 1..10 step 2) {
println(i)
}
}
Output:
1
3
5
7
9
In this example, the range progresses from 1
to 10
, but with a step size of 2
, so it skips every other number.
5. Checking if a Value is in a Range: in
Operator
You can check whether a value falls within a range using the in
operator. This is particularly useful in conditional statements.
Example:
fun main() {
val number = 5
if (number in 1..10) {
println("$number is within the range.")
} else {
println("$number is outside the range.")
}
}
Output:
5 is within the range.
In this case, the program checks whether 5
falls within the range 1..10
.
6. Excluding the End Value: until
If you want to create a range that excludes the end value, you can use the until
function. The until
function creates a range that goes up to, but does not include, the specified end value.
Example:
fun main() {
for (i in 1 until 5) {
println(i)
}
}
Output:
1
2
3
4
Here, the range progresses from 1
to 4
, excluding 5
.
7. Character Ranges
You can create ranges of characters in Kotlin, just as you can with numbers. Character ranges follow the Unicode order, so you can iterate over letters alphabetically.
Example:
fun main() {
for (ch in 'a'..'e') {
println(ch)
}
}
Output:
a
b
c
d
e
Character ranges are useful for alphabetic operations, such as generating sequences of letters.
8. Ranges in Conditional Statements
Ranges are also very handy in conditional statements to check whether a value falls within a specific range of values.
Example:
fun main() {
val age = 25
when (age) {
in 0..12 -> println("Child")
in 13..19 -> println("Teenager")
in 20..64 -> println("Adult")
else -> println("Senior")
}
}
Output:
Adult
In this example, the when
expression uses ranges to classify a person’s age.
Real-World Use Case: Generating Pagination
Let’s say you’re building a web application that supports pagination, and you need to generate a list of page numbers. You can use ranges to easily create the list of page numbers.
Example:
fun main() {
val currentPage = 5
val totalPages = 10
// Generate the list of page numbers for pagination
val pageRange = (1..totalPages).filter { it in (currentPage - 2)..(currentPage + 2) }
println("Page range: $pageRange")
}
Output:
Page range: [3, 4, 5, 6, 7]
In this example, we create a pagination system that displays the current page and two pages before and after it.
Combining Ranges and Progressions
You can combine ranges and progressions to create more complex sequences. For example, you can create reverse ranges with steps:
Example:
fun main() {
for (i in 20 downTo 1 step 3) {
println(i)
}
}
Output:
20
17
14
11
8
5
2
This loop iterates from 20
down to 1
in steps of 3
.
Conclusion
Ranges and progressions in Kotlin provide a powerful way to handle sequences of values efficiently. Whether you’re working with numbers, characters, or conditions, ranges make it easier to iterate, check values, and control loops in a concise and readable manner.
- Use the range operator (
..
) to define a range from a start to an end value. downTo
creates reverse ranges.step
allows you to define the step size in a range.in
checks if a value lies within a range.until
creates ranges that exclude the end value.
Next up, we’ll dive into type checking and typecasting in Kotlin, where you’ll learn how to check the type of objects and safely cast them when necessary. Stay tuned!