Kotlin when Expression
In Kotlin, the when
expression is a conditional expression that allows you to check a value against a set of possible values and execute code based on the matched value. The basic syntax of the when
expression is as follows:
val result = when (value) { option1 -> { // code to execute when value matches option1 value1 } option2 -> { // code to execute when value matches option2 value2 } else -> { // code to execute when value doesn't match any option defaultValue } }
In this syntax, value
is the value to check, option1
and option2
are the possible values to match against, value1
and value2
are the values to return when value
matches option1
or option2
, and defaultValue
is the value to return when value
doesn't match any option. The when
expression returns the value of the matched branch.
Here's an example that demonstrates the use of the when
expression in Kotlin:
fun main() { val day = "Monday" val message = when (day) { "Monday" -> "Today is Monday" "Tuesday" -> "Today is Tuesday" "Wednesday" -> "Today is Wednesday" "Thursday" -> "Today is Thursday" "Friday" -> "Today is Friday" else -> "Today is a weekend day" } println(message) }
In this example, the program checks the value of the day
variable against a set of possible values using the when
expression. If day
is "Monday"
, the program sets message
to the string "Today is Monday"
. If day
is "Tuesday"
, the program sets message
to the string "Today is Tuesday"
, and so on. If day
doesn't match any of the options, the program sets message
to the string "Today is a weekend day"
. Finally, the program prints the value of message
to the console using the println()
function.
It's important to note that in Kotlin, the when
expression can be used to check any value, not just an integer value or an enum value like in some other programming languages. The when
expression can also be used as a statement, in which case it executes the code in the matched branch without returning a value. For example:
when (value) { option1 -> { // code to execute when value matches option1 } option2 -> { // code to execute when value matches option2 } else -> { // code to execute when value doesn't match any option } }
In this example, the when
expression executes the code in the branch that matches the value of value
, or the else
branch if no other branch matches. The when
expression doesn't return a value.