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.[16]

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

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.