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 ...
Get Programming Kotlin now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.