Certainly! The when
expression in Kotlin is similar to a switch statement in other languages. It's used to perform conditional checks on a value and execute different blocks of code based on the value. Here's a simple explanation with an example:
Example
when (value) {
pattern1 -> {
// Code block 1
}
pattern2 -> {
// Code block 2
}
...
else -> {
// Default code block
}
}
Let's say we want to print the name of the day of the week based on the provided number:
fun main() {
val day = 3
val dayOfWeek = when (day) {
1 -> "Sunday"
2 -> "Monday"
3 -> "Tuesday"
4 -> "Wednesday"
5 -> "Thursday"
6 -> "Friday"
7 -> "Saturday"
else -> "Invalid day" // Default case
}
println("Day of the week: $dayOfWeek")
}
Day of the week: Tuesday
when
can also be used as an expression, allowing you to assign its result to a variable.
Example
val type = when (value) {
is String -> "String"
is Int -> "Int"
else -> "Unknown"
}
You can combine multiple conditions using commas ,
or ranges.
Example
val result = when (value) {
in 1..10 -> "Range from 1 to 10"
in 11..20 -> "Range from 11 to 20"
else -> "Outside the range"
}
You can check multiple values in a single branch using the in
operator.
Example
val result = when (value) {
1, 3, 5 -> "Odd"
2, 4, 6 -> "Even"
else -> "Unknown"
}
The when
expression in Kotlin provides a flexible and concise way to perform conditional checks based on the value of an expression. It's versatile and can handle various scenarios, making it a powerful tool for writing clean and readable code.