Ranges with When

It is also possible to match cases in range form. To make use of ranges, Kotlin provides the in operator. Using the in operator, we are asking for a value that is contained within a given range. This is specifically useful when more than one condition has the same result:

fun main(args: Array<String>) {
val grade = "A"
when (grade) {
in "A".."E" -> println("You are promoted to the next level")
"F" -> println("You need hard work.")
else -> println("Invalid input")
}
}

In this example, if the student grade is within the range of A to E then a You are promoted to the next level message will be displayed. If the grade is F, then You need hard work. will be displayed on the screen; otherwise, Invalid input is displayed.

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

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