官术网_书友最值得收藏!

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:

主站蜘蛛池模板: 西充县| 长岭县| 井研县| 安乡县| 宁晋县| 霍州市| 公主岭市| 驻马店市| 湖南省| 营山县| 大新县| 易门县| 乐昌市| 红安县| 固阳县| 南和县| 墨脱县| 宁陵县| 南安市| 吉木乃县| 岗巴县| 保康县| 屏边| 白玉县| 丰城市| 渭源县| 莱西市| 桦川县| 绿春县| 柳州市| 河津市| 平舆县| 得荣县| 泾源县| 鄂尔多斯市| 通海县| 宕昌县| 乌鲁木齐县| 绩溪县| 宁明县| 黄大仙区|