Another expression that controls the flow of execution in a program is the when
expression.
A when
expression is made up of multiple branches that contain values, or arguments, to check for. If the value of the variable being evaluated matches one of the branches’ arguments the instructions contained in that branch will be executed.
For example:
var lightColor = "red" when (lightColor) { "green" -> println("Go.") "yellow" -> println("Slow down.") "red" -> println("Stop.") else -> println("Not a valid traffic light color.") } // Prints: Stop.
- The keyword
when
is followed by a variable placed within parentheses. - The set up for each branch starts with a value to check for, an arrow(
->
), and then an instruction to execute. - The
else
at the end of awhen
expression is an optional addition that can be used to catch any unexpected or additional values the variable being evaluated could contain.
In the example above, the value of lightColor
was "red"
, so the instruction println("Stop.")
was executed.
Programmers often use when
expressions in lieu of if
/else
, else
-if
conditionals because of their significantly shorter syntax. For example, we can create a when
expression that evaluates multiple expressions:
var num = 19 when { num < 0 -> println("$num is negative.") num == 0 -> println("$num is zero.") num > 0 -> println("$num is positive.") else -> println("Not a valid number.") } // Prints: 19 is positive.
Note how in the example above, we did not place a value inside parentheses after the when
keyword and instead placed full expressions inside the branches’ arguments.
To explore other ways we can implement a when
expression in our programs, check out the Kotlin Language Guide.
Instructions
We’re going to create a program that determines what kind of crop to grow based on the season.
Create a when
expression that evaluates the value of the variable season
.
When the value of season
is:
"Winter"
, print"Grow kale."
"Spring"
, print"Grow lettuce."
"Summer"
, print"Grow corn."
"Fall"
, print"Grow pumpkins."
Add an else
expression that prints "Not a valid season."
Optional
Take some time to experiment with your code by changing the value of season
and running your program.