When expression
The classic switch
statement has been supported in many languages, including C, C++, and Java, but is rather restrictive. At the same time, the functional programming concept of pattern matching has become more mainstream. Kotlin blends the two, and offers when
, a more powerful alternative to switch
while not going quite as far as full pattern matching.
There are two forms of when
. The first is similar to switch
, accepting an argument, and with a series of conditions, each of which is checked in turn against the value. The second is without an argument and used as a replacement for a series of if...else
conditions.
When (value)
The simplest example of when
is matching against different constants, which will be familiar as the typical usage of switch
in a language like Java:
fun whatNumber(x: Int) { when (x) { 0 -> println("x is zero") 1 -> println("x is 1") else -> println("X is neither 0 or 1") }...