In Kotlin, the when
expression is a versatile and concise way to handle multiple conditions. It’s often used as an alternative to long chains of if-else
statements, allowing you to evaluate multiple conditions in a clean and readable way. The when
expression is more flexible than a simple switch statement found in other languages, as it can evaluate any type of value, not just numbers or enums.
In this article, we’ll explore the various ways to use the when
expression in Kotlin, from handling basic cases to using complex conditions, ranges, and types. By the end, you’ll understand how to use when
to simplify your conditional logic.
What is the when
Expression?
The when
expression evaluates a value and matches it against multiple possible cases. When a match is found, the corresponding block of code is executed. Unlike if-else
, when
can return a value and handle complex conditions such as ranges, types, and arbitrary expressions.
Syntax:
when (value) {
case1 -> {
// Execute this block
}
case2 -> {
// Execute this block
}
else -> {
// Default case
}
}
1. Basic when
Expression
The simplest form of the when
expression matches a single value against multiple cases.
Example:
fun main() {
val number = 3
when (number) {
1 -> println("One")
2 -> println("Two")
3 -> println("Three")
else -> println("Unknown number")
}
}
Output:
Three
In this example, number
is compared against the values 1
, 2
, and 3
. Since number
is 3
, the corresponding block prints "Three"
. The else
branch acts as a default case, which is executed if none of the other cases match.
2. Using when
as an Expression
In Kotlin, when
can be used as an expression, meaning it can return a value. This makes it similar to the if
expression in Kotlin, where you can assign the result of the when
expression to a variable.
Example:
fun main() {
val number = 2
val result = when (number) {
1 -> "One"
2 -> "Two"
3 -> "Three"
else -> "Unknown number"
}
println(result) // Output: Two
}
Here, the when
expression returns a value based on the input number
and assigns it to the variable result
.
3. Multiple Cases in a Single Branch
You can combine multiple cases into a single branch using commas, making the when
expression even more concise.
Example:
fun main() {
val number = 4
when (number) {
1, 3, 5 -> println("Odd number")
2, 4, 6 -> println("Even number")
else -> println("Unknown number")
}
}
Output:
Even number
In this example, the values 1
, 3
, and 5
share the same branch, as do 2
, 4
, and 6
. This reduces repetition and keeps the code clean.
4. when
with Ranges
Kotlin allows you to use ranges within a when
expression, which is particularly useful for checking whether a value falls within a specific range.
Example:
fun main() {
val age = 25
when (age) {
in 0..12 -> println("Child")
in 13..19 -> println("Teenager")
in 20..64 -> println("Adult")
else -> println("Senior")
}
}
Output:
Adult
Here, the when
expression checks whether the age
falls within specific ranges, printing the appropriate life stage based on the value.
5. when
with Type Checking
The when
expression can also be used to check the type of a variable using the is
keyword. This is particularly useful when dealing with objects that can belong to multiple types.
Example:
fun main() {
val obj: Any = "Kotlin"
when (obj) {
is String -> println("It's a String of length ${obj.length}")
is Int -> println("It's an Integer")
else -> println("Unknown type")
}
}
Output:
It's a String of length 6
In this example, the when
expression checks the type of obj
. Since obj
is a String
, the corresponding branch is executed, and the length of the string is printed.
6. when
without an Argument
You can use when
without an argument, essentially turning it into a more readable alternative to an if-else
chain. In this case, each branch is evaluated as a Boolean expression.
Example:
fun main() {
val number = 15
when {
number % 2 == 0 -> println("Even number")
number % 2 != 0 -> println("Odd number")
else -> println("Unknown number")
}
}
Output:
Odd number
Here, the when
expression evaluates conditions directly without checking against a specific value.
7. Returning Values from when
Expressions
As mentioned earlier, when
can return a value. This feature is particularly useful for assigning results to variables based on different conditions.
Example:
fun main() {
val score = 85
val grade = when {
score >= 90 -> "A"
score >= 80 -> "B"
score >= 70 -> "C"
score >= 60 -> "D"
else -> "F"
}
println("Grade: $grade") // Output: Grade: B
}
In this example, the when
expression returns a grade based on the value of score
.
8. Combining Complex Conditions
The when
expression supports complex conditions, including logical operators like &&
and ||
. This makes when
flexible enough to handle a variety of logical scenarios.
Example:
fun main() {
val age = 30
val hasID = true
when {
age >= 18 && hasID -> println("You can enter the event.")
age >= 18 && !hasID -> println("You need an ID to enter.")
else -> println("You are not allowed to enter.")
}
}
Output:
You can enter the event.
In this example, the when
expression evaluates multiple conditions using logical operators to handle different scenarios.
Real-World Use Case: Simple Calculator
Let’s build a simple calculator that takes two numbers and an operator as input, then performs the corresponding arithmetic operation using the when
expression.
Example:
fun main() {
val num1 = 10
val num2 = 5
val operator = "/"
val result = when (operator) {
"+" -> num1 + num2
"-" -> num1 - num2
"*" -> num1 * num2
"/" -> if (num2 != 0) num1 / num2 else "Cannot divide by zero"
else -> "Unknown operator"
}
println("Result: $result") // Output: Result: 2
}
In this calculator example, the when
expression checks the operator and performs the appropriate operation. It also handles division by zero safely.
Conclusion
The when
expression in Kotlin is a powerful, flexible tool for handling multiple conditions. It provides a clean and concise alternative to if-else
chains, making your code more readable and expressive.
- Use
when
to match values and return results based on multiple conditions. - Combine multiple cases in a single branch to reduce repetition.
- Use ranges, type checking, and Boolean expressions to handle complex logic.
- Leverage
when
as an expression to return values, making your code more concise. - The
when
expression can act as a replacement forswitch
statements andif-else
ladders, giving you more flexibility.
Next up, we’ll explore break
and continue
statements in Kotlin, where you’ll learn how to control the flow of loops by exiting early or skipping iterations. Stay tuned!