The when expression

## The when expression

It's quite common that you need to execute different code depending on the value of a variable. You can of course do this by a sequence of if... else if ... else if ... else statements, but there is a more readable alternative (when1.kts):

import org.otfried.cs109.readString

when (choice) {
"orange" -> println("Here's an orange")
"green" -> println("It greens so green in Spain")
"gray", "grey", "black" -> println("Huh?  That's not a color.")
"red" -> println("Roses are red")
"pink" -> println("Pretty in pink")
"blue" -> println("Are you feeling blue?")
else -> println("That's an uncommon answer")
}


Note that you can provide several choices in one when case (our response to gray, grey, and black is the same).

Like if, the when expression really is an expression and can return a value, so we can rewrite the code above like this (when2.kts):

import org.otfried.cs109.readString

val response = when (choice) {
"orange" -> "Here's an orange"
"green" -> "It greens so green in Spain"
"gray", "grey", "black" -> "Huh?  That's not a color."
"red" -> "Roses are red"
"pink" -> "Pretty in pink"
"blue" -> "Are you feeling blue?"
else -> "That's an uncommon answer"
}
println(response)


Each when case must contain exactly one expression. If you want to leave a case empty, or perform two statements, you need to put a block in curly braces (when3.kts):

import org.otfried.cs109.readString

var reddish = false
when (choice) {
"orange" -> { println("Here's an orange"); reddish = true }
"green" -> println("It greens so green in Spain")
"gray", "grey", "black" -> println("Huh?  That's not a color.")
"red" -> { println("Roses are red"); reddish = true }
"pink" -> { println("Pretty in pink"); reddish = true }
"blue" -> println("Are you feeling blue?")
"white" -> { /* do nothing */ }
else -> println("That's an uncommon answer")
}
if (reddish)
println("Another lover of reddish tones")


Instead of single choices, you can also provide a collection of choices, such as a range of integers or a set (when4.kts):

fun opinion(x: Int) {
when (x) {
0, 1 -> println("A binary digit")
in 0..9 -> println("A decimal digit")
in setOf(16, 25, 36, 49, 64, 81, 100) -> println("A square")
!in 0..100 -> println("Not a two-digit number")
}
}

 The when expression