Use Of 'when'
fun main(args: Array<String>) {
val x:Int = 10
when (x) {
1 -> println("x is 1")
2 -> println("x is 2")
else -> {
println("x is neither 1 nor 2")
}
}
}
In the above sample, the Kotlin compiler matches the value of x with the given branch conditions. If it doesn't match any of the branches, then it will execute the else part. 'when' is equivalent to multiple if block. Kotlin provides another flexibility to the developer, where the developer can provide multiple checks in the same line by putting“,” inside the branches. Let us modify the above sample here:
fun main(args: Array<String>) {
val x:Int = 10
when (x) {
1,2 -> println(" The value of X either 1,2")
else -> {
println("x is neither 1 nor 2")
}
}
}
There is another flexibility instead of using only constants, we can also use arbitrary expressions as a branch condition. Here is the code snippet:
fun main(args: Array<String>) {
val x:Int = 10
val s: String = "10"
when (x) {
parseInt(s) -> println(" The value of X is $s ")
else -> {
println("No Branch Found")
}
}
}
We can also use range as a branch condition using in and !in. Here is the code snippet:
fun main(args: Array<String>) {
val x:Int = 10
when (x) {
in 1..10 -> println(" Range 1 to 10")
in 11..20 -> println(" Range 10 to 20")
!in 10..20 -> println(" Range not in 10 to 20")
else -> {
println("Not in the range")
}
}
}
We can also check the particular type by using is and !is. Here is the code snippet:
fun main(args: Array<String>) {
val x:Any = 100
when (x) {
is Int -> println(" Type is Int")
is String -> println(" Type is String")
!is Double -> println(" Type is not Double")
else -> {
println("No Type Found")
}
}
}
fun main(args: Array<String>) {
val x:Int = 10
when {
x.isOdd() -> println("x is odd")
x.isEven() -> println("x is even")
else -> {
println("x is neither odd nor even")
}
}
}
We can also use enum along with 'when'. Here is the code snippet:
fun main(args: Array<String>) {
when (KotlinEnumTest.NORTH) {
KotlinEnumTest.NORTH -> println(KotlinEnumTest.WEST)
KotlinEnumTest.WEST -> println(KotlinEnumTest.NORTH)
else -> {
println("No Condition Matched")
}
}
}
enum class KotlinEnumTest {
NORTH, SOUTH, WEST, EAST
}
One more thing, The scope of variables in 'when' subject would be restricted to 'when' body.
val x:Int = 10
when {
x.isOdd() -> println("x is odd")
x.isEven() -> println("x is even")
else -> {
println("x is neither odd nor even")
}
}
}
We can also use enum along with 'when'. Here is the code snippet:
fun main(args: Array<String>) {
when (KotlinEnumTest.NORTH) {
KotlinEnumTest.NORTH -> println(KotlinEnumTest.WEST)
KotlinEnumTest.WEST -> println(KotlinEnumTest.NORTH)
else -> {
println("No Condition Matched")
}
}
}
enum class KotlinEnumTest {
NORTH, SOUTH, WEST, EAST
}
One more thing, The scope of variables in 'when' subject would be restricted to 'when' body.
I think, Now we have enough knowledge about 'when' in Kotlin.
Good approach to achieve switch functionality. Thanks for sharing.
ReplyDelete