- Kotlin Programming By Example
- Iyanu Adelekan
- 236字
- 2021-08-27 20:00:10
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:

- Cocos2d Cross-Platform Game Development Cookbook(Second Edition)
- 零基礎搭建量化投資系統:以Python為工具
- TypeScript Blueprints
- Implementing Cisco Networking Solutions
- 鋒利的SQL(第2版)
- 深入淺出RxJS
- Learning Concurrency in Kotlin
- Go語言編程
- Couchbase Essentials
- 運維前線:一線運維專家的運維方法、技巧與實踐
- Web開發的平民英雄:PHP+MySQL
- DevOps 精要:業務視角
- 用Python動手學統計學
- 嵌入式Linux與物聯網軟件開發:C語言內核深度解析
- ASP.NET 4權威指南