Using range with the when expression
In Kotlin, when is like a super-powered switch control statement. However, that's not all it can do. There's a lot of amazing logic that you can build with the when statement, one example of which is using a range with the when statement. We will take a look at that in this recipe.
Getting ready
You need to install a preferred development environment that compiles and runs Kotlin. You can also use the command line for this purpose, for which you need Kotlin compiler installed, along with JDK. I am using the command line to compile and run my Kotlin code for this recipe.
How to do it...
First, let's create a file, name it whenWithRanges.kt, and follow these steps:
- Let's try a basic
whenstatement to understand how it works:
fun main(args: Array<String>) {
val x = 12
when(x){
12 -> println("x is equal to 12")
4 -> println("x is equal to 4")
else -> println ("no conditions match!")
}
}So basically, this...