Combining cases

The When expression allows us to combine more than one cases in one line. In order to match with the expression, we concatenate more than one case in a comma-separated list:

fun main(args: Array<String>) {
val grade = "b"
when (grade) {
"A","a" -> println("Excellent")
"B","b" -> println("Very Good")
"C","c" -> println("Nice work")
"D","d" -> println("OK")
"E","e" -> println("Hmmm")
"F","f" -> println("Better luck next time")
else -> println("Invalid input")
}
}

In this example, a user can enter the student's grade without worrying about whether the keyboard caps lock is on or off. If input is "a" or "A", either way the output will be Excellent.

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

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