Saturday, 4 April 2020

Switch Case in Kotlin


Use Of 'when'


If you are familiar with any programming languages like C, C++ or Java, you might have heard the term switch statement, when there are multiple conditions and based on input we need to execute a condition. It's a replacement of multiple if-else statements. “when” operator matches the variable value against the branch conditions. If it satisfies the branch condition then it will execute the statement inside that scope. Here is a sample code snippet:

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")
        }
    }
}

It can also be used as if-else if chain. If no argument is passed along with 'when' keyword, the branches condition would be boolean and the branch condition is executed when true. Here is the code snippet:

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.

I think, Now we have enough knowledge about 'when' in Kotlin.

Happy Learning!!

1 comment:

  1. Good approach to achieve switch functionality. Thanks for sharing.

    ReplyDelete

Visibility Modifier In Kotlin

Visibility Modifier The visibility modifier basically defines a scope from where it can be visible and accessible. There are four visi...