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

There's more...

Range expressions can enhance use of the when expression as well. In the following example, we are going to implement a simple function that will be responsible for mapping a student's exam score to a corresponding grade. Let's say we have the following enum class model for student grades:

enum class Grade { A, B, C, D }

We can define a function that will map the exam score value, in the 0 to 100 % range, to the proper grade (A, B, C, or D) using a when expression, as follows:

fun computeGrade(score: Int): Grade =
when (score) {
in 90..100 -> Grade.A
in 75 until 90 -> Grade.B
in 60 until 75 -> Grade.C
in 0 until 60 -> Grade.D
else -> throw IllegalStateException("Wrong score value!")
}

Using ranges together with the in operator makes the implementation of the computeGrade() function much cleaner and more natural than the classic equivalent implementation using traditional comparison operators, such as <, >, <=, and >=.

主站蜘蛛池模板: 奈曼旗| 凤台县| 司法| 中方县| 清水县| 长子县| 巩义市| 桂东县| 沽源县| 泽州县| 墨竹工卡县| 揭阳市| 通化市| 高碑店市| 宜兴市| 晋城| 仪陇县| 栾川县| 临漳县| 静乐县| 彭阳县| 和平县| 巴彦县| 三明市| 安泽县| 合作市| 大庆市| 澄江县| 永康市| 黔南| 巴林右旗| 天气| 西乡县| 双柏县| 织金县| 会同县| 隆安县| 文昌市| 盐津县| 喜德县| 洛扎县|