How to Use When with Ranges in Kotlin: Simple Guide
In Kotlin, you can use the
when expression with ranges by placing a range like 1..10 as a condition. The when block checks if the value falls inside the range and executes the matching branch. This makes it easy to test if a number is within certain intervals.Syntax
The when expression uses ranges as conditions by specifying a range like start..end. If the value matches the range, the corresponding block runs.
value: The variable you want to check.start..end: Defines the range to test.- Branches: Code executed when the value is in the range.
else: Optional default case if no ranges match.
kotlin
when (value) {
in start..end -> {
// code if value is in the range
}
else -> {
// code if value is not in any range
}
}Example
This example shows how to use when with ranges to print messages based on a number's range.
kotlin
fun main() {
val number = 25
when (number) {
in 1..10 -> println("Number is between 1 and 10")
in 11..20 -> println("Number is between 11 and 20")
in 21..30 -> println("Number is between 21 and 30")
else -> println("Number is out of range")
}
}Output
Number is between 21 and 30
Common Pitfalls
Common mistakes include:
- Using
==instead ofinto check ranges. - Forgetting that ranges are inclusive of both ends.
- Not covering all possible values, missing an
elsebranch.
Always use in to check if a value is inside a range.
kotlin
fun main() {
val number = 15
// Wrong: using == instead of in
when (number) {
1..10 -> println("Between 1 and 10") // This compares reference, not range
else -> println("Other")
}
// Right way:
when (number) {
in 1..10 -> println("Between 1 and 10")
else -> println("Other")
}
}Output
Other
Other
Quick Reference
Tips for using when with ranges:
- Use
in start..endto check if a value is inside a range. - Ranges include both start and end values.
- Always add an
elsebranch to handle unexpected values. whencan replace multipleif-elsechecks for cleaner code.
Key Takeaways
Use the keyword
in inside when to check if a value falls within a range.Ranges in Kotlin are inclusive, meaning both start and end values are included.
Always provide an
else branch in when to cover all cases.Using
when with ranges makes your code cleaner and easier to read than multiple if-else statements.