July 2018
Intermediate to advanced
242 pages
8h 6m
English
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 ...
Read now
Unlock full access