...

/

When It’s Time to Use when

When It’s Time to Use when

Kotlin doesn’t have switch; instead it has when, and that comes in different flavors: as expression and as statement.

when as an expression

Here’s an implementation of the function to determine if a cell will be alive in the next generation in Conway’s Game of Life.

Press + to interact
fun isAlive(alive: Boolean, numberOfLiveNeighbors: Int): Boolean {
if (numberOfLiveNeighbors < 2) { return false }
if (numberOfLiveNeighbors > 3) { return false }
if (numberOfLiveNeighbors == 3) { return true }
return alive && numberOfLiveNeighbors == 2
}

This code tells if a cell will live in the next generation, but any programmer reading such code may quickly lose motivation to live; the code is too noisy, verbose, repetitive, and error prone.

In the simplest form, when can replace a series of if-else statements or expressions. Now is a great time to refactor that code to use Kotlin’s when.

Press + to interact
fun isAlive(alive: Boolean, numberOfLiveNeighbors: Int) = when {
numberOfLiveNeighbors < 2 -> false
numberOfLiveNeighbors > 3 -> false
numberOfLiveNeighbors == 3 -> true
else -> alive && numberOfLiveNeighbors == 2
}

The previous version of the function specified the return type and used the block structure for the method body. In this version, the refactored code uses type inference and the single-expression function syntax. Here, when is used as an expression. The value returned by the function is the value returned by one of the branches in when.

The two versions of the isAlive() function produce the same results for ...