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 O’Reilly online learning.
O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.