When With Ranges
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 33 of 93.
Sometimes you need to check if a value falls within a range rather than matching specific values. The when expression supports this using the in keyword combined with ranges.
fun main() {
val score = 85
val grade = when (score) {
in 90..100 -> "A"
in 80..89 -> "B"
in 70..79 -> "C"
in 60..69 -> "D"
else -> "F"
}
println(grade) // Prints: B
}The in keyword checks if the value exists within the specified range. Here, 85 falls within 80..89, so the grade is "B". This is much cleaner than writing score >= 80 && score <= 89 for each condition.
You can also combine ranges with specific values in the same when expression:
fun main() {
val age = 17
val category = when (age) {
0 -> "Newborn"
in 1..12 -> "Child"
in 13..19 -> "Teenager"
else -> "Adult"
}
println(category) // Prints: Teenager
}Ranges make your code more readable when dealing with continuous numeric conditions, which is common in grading systems, age categories, and similar scenarios.
Challenge
EasyWrite a function getTicketPrice that takes age and returns the ticket price based on the person's age category.
Use a when expression with ranges to determine the appropriate ticket price.
Conditions:
- Age
0to3: return0(free) - Age
4to12: return10(child price) - Age
13to17: return15(teen price) - Age
18to64: return25(adult price) - Age
65and above: return12(senior price)
Parameters:
age(Int): The person's age
Returns: The ticket price as an integer (Int)
Try it yourself
fun getTicketPrice(age: Int): Int {
// Write code here
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground