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 tested in the when expression.

Here, the it refers to the current value being iterated upon by the forEach method. The % operator is a binary operator that acts on two operands. It divides the first operand by the second and returns the remainder of the division. Thus, the when expression tests if/when the current value iterated upon (the value held within it) is divided by 2 and has a remainder of 0. If it does, the value is even and hence the value is printed.

To observe how the program works, copy and paste the preceding code into a file, then compile and run the program:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.158.36