Using Ranges in When
Svep för att visa menyn
Using Ranges in When in Kotlin
Kotlin lets you use ranges in a when expression to check if a value is within a specific sequence of numbers or characters. This makes your code cleaner and easier to read than using multiple comparisons.
What Is a Range?
A range in Kotlin is a sequence of values with a start and an end, such as 1..10 for numbers or 'a'..'z' for characters. You can use the in keyword to check if a value belongs to a range.
Why Use Ranges in When?
- Simplifies checking if a value is between two limits;
- Makes code more readable and concise;
- Reduces the need for multiple logical conditions.
Basic Syntax
when (value) {
in 1..10 -> println("Value is between 1 and 10")
!in 11..20 -> println("Value is not between 11 and 20")
else -> println("Value is something else")
}
Typical Use Cases
- Checking if a user's age is within a valid range;
- Grouping scores into letter grades;
- Validating if a character is a letter or digit.
Using ranges in when expressions helps you write safer, more expressive code when working with intervals.
Main.kt
Tack för dina kommentarer!
Fråga AI
Fråga AI
Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal
Using Ranges in When
Using Ranges in When in Kotlin
Kotlin lets you use ranges in a when expression to check if a value is within a specific sequence of numbers or characters. This makes your code cleaner and easier to read than using multiple comparisons.
What Is a Range?
A range in Kotlin is a sequence of values with a start and an end, such as 1..10 for numbers or 'a'..'z' for characters. You can use the in keyword to check if a value belongs to a range.
Why Use Ranges in When?
- Simplifies checking if a value is between two limits;
- Makes code more readable and concise;
- Reduces the need for multiple logical conditions.
Basic Syntax
when (value) {
in 1..10 -> println("Value is between 1 and 10")
!in 11..20 -> println("Value is not between 11 and 20")
else -> println("Value is something else")
}
Typical Use Cases
- Checking if a user's age is within a valid range;
- Grouping scores into letter grades;
- Validating if a character is a letter or digit.
Using ranges in when expressions helps you write safer, more expressive code when working with intervals.
Main.kt
Tack för dina kommentarer!