when
This post shows multiple ways in which we can use the when block in Kotlin
We can start with a typical use of when (like in switch statements)
enum class Season {
SPRING, SUMMER, FALL, WINTER
}
To execute logic based on the season, we write the below snippet of code
when (timeOfYear) {
Season.SPRING -> println("Flowers are blooming")
Season.SUMMER -> println("It's hot!")
Season.FALL -> println("It's getting cooler")
Season.WINTER -> println("I need a coat")
}
In case we wanted to get the value rather than print based on the timeOfYear, we can use the below snippet of code, where we return the value and it can be returned in the overall when block
val str = when (timeOfYear) {
Season.SPRING -> "Flowers are blooming"
Season.SUMMER -> "It's hot!"
Season.FALL -> "It's getting cooler"
Season.WINTER -> {
"I need a coat"
}
}
println(str)
Let's now consider some of the conditional executions we might have in java like below
val num2 = -50
if (num < num2) {
println("num is less than num2")
} else if (num > num2) {
println("num is greater than num2")
} else {
println("num = num2")
}
These can be easily replaced with the when block in Kotlin as given below
when {
num < num2 -> println("num is less than num2")
num > num2 -> println("num is greater than num2")
else -> println("num = num2")
}
Similarly, when we wanted to check for range of values, we can use snippet of code as given below
when (num) {
in 100..199 -> println("in range 100..199")
200 -> println("200")
300 -> println("300")
else -> println("Doesn't match anything")
}
Let's consider the use of the expressions based on which some branching or execution to be made, in that case we can use the snippet below
val y = 10
when (num) {
y + 80 -> println("90")
y + 90 -> println("100")
300 -> println("300")
else -> println("Doesn't match anything")
}
When we wanted to switch based on the type of a variable, we can use the below given snippet
val z = when (something) {
is String -> {
println(something.toUpperCase())
}
is BigDecimal -> {
println(something.remainder(BigDecimal(10.5)))
}
is Int -> {
println("${something - 22}")
}
else -> {
println("I have no idea what type this is")
}
}
println(z)
The same case above with a return value can be written as below.
The sample declarations are given below
val obj: Any = "I'm a string"
val obj2: Any = BigDecimal(25.2)
val obj3: Any = 45
val something: Any = obj2
val z = when (something) {
is String -> {
println(something.toUpperCase())
1
}
is BigDecimal -> {
println(something.remainder(BigDecimal(10.5)))
2
}
is Int -> {
println("${something - 22}")
3
}
else -> {
println("I have no idea what type this is")
-1
}
}
println(z)
Comments
Post a Comment