Introduction
The when
statement in Kotlin is a powerful control flow statement that allows you to choose between multiple possible execution paths based on the value of an expression. It is similar to the switch
statement found in other programming languages, but more expressive and versatile. This chapter will cover the syntax and usage of the when
statement with examples.
Basic when Statement
The when
statement evaluates a given expression and executes the corresponding branch of code based on the value of the expression.
Syntax
when (expression) {
value1 -> {
// Code to execute if expression == value1
}
value2 -> {
// Code to execute if expression == value2
}
else -> {
// Code to execute if expression does not match any value
}
}
Example
fun main() {
val dayOfWeek = 3
when (dayOfWeek) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday")
4 -> println("Thursday")
5 -> println("Friday")
6 -> println("Saturday")
7 -> println("Sunday")
else -> println("Invalid day")
}
}
Explanation:
when (dayOfWeek)
: Thewhen
statement evaluates the value ofdayOfWeek
.- The branch corresponding to
3
is executed, printing "Wednesday" to the console.
Using Multiple Conditions
You can combine multiple conditions in a single branch by separating them with commas.
Syntax
when (expression) {
value1, value2 -> {
// Code to execute if expression == value1 or expression == value2
}
else -> {
// Code to execute if expression does not match any value
}
}
Example
fun main() {
val number = 3
when (number) {
1, 3, 5, 7, 9 -> println("Odd number")
2, 4, 6, 8, 10 -> println("Even number")
else -> println("Number not in range 1-10")
}
}
Explanation:
- The branch corresponding to
3
is executed, printing "Odd number" to the console.
Using when as an Expression
In Kotlin, when
can also be used as an expression that returns a value. This is useful when you want to assign a value based on a condition.
Syntax
val result = when (expression) {
value1 -> result1
value2 -> result2
else -> defaultResult
}
Example
fun main() {
val number = 4
val parity = when (number) {
1, 3, 5, 7, 9 -> "Odd"
2, 4, 6, 8, 10 -> "Even"
else -> "Unknown"
}
println("Number $number is $parity")
}
Explanation:
- The expression evaluates to "Even" because
number
is4
. parity
is assigned the value "Even".- The output is "Number 4 is Even".
Checking Types with when
The when
statement can be used to check the type of an expression.
Syntax
when (expression) {
is Type1 -> {
// Code to execute if expression is of Type1
}
is Type2 -> {
// Code to execute if expression is of Type2
}
else -> {
// Code to execute if expression is of neither Type1 nor Type2
}
}
Example
fun main() {
val obj: Any = "Hello"
when (obj) {
is String -> println("obj is a String of length ${obj.length}")
is Int -> println("obj is an Int with value $obj")
is Double -> println("obj is a Double with value $obj")
else -> println("Unknown type")
}
}
Explanation:
- The expression
obj
is evaluated. - Since
obj
is aString
, the branch forString
is executed, printing "obj is a String of length 5".
Using when without an Argument
You can use when
without an argument to evaluate multiple Boolean conditions.
Syntax
when {
condition1 -> {
// Code to execute if condition1 is true
}
condition2 -> {
// Code to execute if condition2 is true
}
else -> {
// Code to execute if none of the conditions are true
}
}
Example
fun main() {
val number = -10
when {
number > 0 -> println("Number is positive")
number < 0 -> println("Number is negative")
else -> println("Number is zero")
}
}
Explanation:
- The first condition checks if
number
is greater than 0. - The second condition checks if
number
is less than 0. - Since
number
is-10
, the second condition is true, and "Number is negative" is printed.
Example Program with when Statement
Here is an example program that demonstrates the use of various forms of the when
statement in Kotlin:
fun main() {
val day = 3
// Basic when statement
when (day) {
1 -> println("Monday")
2 -> println("Tuesday")
3 -> println("Wednesday")
4 -> println("Thursday")
5 -> println("Friday")
6 -> println("Saturday")
7 -> println("Sunday")
else -> println("Invalid day")
}
val number = 4
// when as an expression
val parity = when (number) {
1, 3, 5, 7, 9 -> "Odd"
2, 4, 6, 8, 10 -> "Even"
else -> "Unknown"
}
println("Number $number is $parity")
val obj: Any = 123.45
// Checking types with when
when (obj) {
is String -> println("obj is a String of length ${obj.length}")
is Int -> println("obj is an Int with value $obj")
is Double -> println("obj is a Double with value $obj")
else -> println("Unknown type")
}
// when without argument
val temperature = 30
when {
temperature < 0 -> println("It's freezing")
temperature in 0..15 -> println("It's cold")
temperature in 16..25 -> println("It's mild")
temperature > 25 -> println("It's warm")
else -> println("Unknown temperature")
}
}
Conclusion
In this chapter, you learned about the when
statement in Kotlin, including its syntax and usage with multiple conditions, as an expression, and for type checking. You also saw how to use when
without an argument to evaluate multiple Boolean conditions. The when
statement is a powerful and flexible tool for making decisions in your Kotlin programs.