The when expression

The when expression is another means of controlling program flow. Let's observe how it works with a simple example:

fun printEvenNumbers(numbers: Array<Int>) {  numbers.forEach {    when (it % 2) {      0 -> println(it)    }  }}fun main (args: Array<String>) {  val numberList: Array<Int> = arrayOf(1, 2, 3, 4, 5, 6)  printEvenNumbers(numberList)}

The preceding printEvenSum function takes an integer array as its only argument. We will cover arrays later on in this chapter, but for now think of them as a sequential collection of values existing in a value space. In this case, the array passed contains values that exist in the value space of integers. Each element of the array is iterated upon using the forEach method and each number is ...

Get Kotlin Programming By Example 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.