Kotlin when with Ranges 🎯

beginner
5 min

Kotlin when with Ranges 🎯

Welcome to this in-depth guide on using the when expression with ranges in Kotlin! In this tutorial, we'll explore how to make decisions based on ranges using the when expression, a versatile feature of Kotlin that makes your code more readable and easier to understand.

Before we dive in, let's review the basic syntax of the when expression in Kotlin:

kotlin
when (expression) { condition1 -> action1 condition2 -> action2 // ... more conditions and actions else -> defaultAction }

Why Use Ranges in when? 💡

Using ranges in the when expression allows you to simplify your code and make it more expressive when checking for values within a specific range. Ranges in Kotlin can be represented as start..end or start until end.

Basic Examples 📝

Let's start with some basic examples to understand the concept better.

kotlin
fun main() { val number = 10 when (number) { in 1..10 -> println("Number is between 1 and 10") in 11..20 -> println("Number is between 11 and 20") else -> println("Number is not within the given ranges") } }

In this example, we check if the number is within the ranges of 1 to 10 and 11 to 20.

Quick Quiz
Question 1 of 1

What will be the output of the above code?

Practical Application 🎯

Now let's make things more interesting by applying this concept to a practical example. Imagine we're creating a ticket booking system for a movie theater. We want to offer different pricing based on the age of the customer.

kotlin
fun main() { val age = 15 when (age) { in 0..2 -> println("Child: $2.00") in 3..12 -> println("Child: $4.00") in 13..17 -> println("Youth: $6.00") in 18..59 -> println("Adult: $8.00") in 60..Int.MAX_VALUE -> println("Senior: $6.00") else -> println("Invalid age") } }

In this example, we calculate the ticket price based on the customer's age.

Quick Quiz
Question 1 of 1

What will be the output of the above code for a customer aged 15?

Conclusion 📝

In this tutorial, we learned about using the when expression with ranges in Kotlin. We discussed the basics, explored practical applications, and even put our knowledge to the test with a quiz. As you continue to learn and practice, you'll find the when expression with ranges to be a powerful tool in your programming arsenal, making your code more readable and expressive.

Stay tuned for more tutorials on Kotlin and happy coding! 💡🎯🎥