Menu
Coddy logo textTech

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 icon

Challenge

Easy

Write 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 0 to 3: return 0 (free)
  • Age 4 to 12: return 10 (child price)
  • Age 13 to 17: return 15 (teen price)
  • Age 18 to 64: return 25 (adult price)
  • Age 65 and above: return 12 (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
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Kotlin playground