O'Reilly logo

Programming Kotlin by Stefan Bocutiu, Stephen Samuel

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required