Kotlin When Statement & Expression


Kotlin When Statement

Kotlin's when is another way of writing conditional statements in Kotlin. When you have multiple conditions, writing it using an if-else statement becomes less readable. To improve the readability, you can use the when statement. Let's take some examples - 
    val animal = "Dog"
    
    if(animal == "Cat")
    {
    	println("Animal is Cat")
    }
    else if(animal == "Dog")
    {
    	println("Animal is Dog")
    }
    else if(animal == "Horse")
    {
    	println("Animal is Horse")
    }
    else
    {
    	println("Animal Not Found")
    }

Although this code works but having multiple conditions with multiple statements inside every block becomes cumbersome to understand later. We need more readable code. To improve this simple program we can make use of the when statement 
    val animal = "Dog"

    when(animal)
    {
    	"Cat" -> println("Animal is Cat")
        "Dog" -> println("Animal is Dog")
        "Horse" -> println("Animal is Horse")
        else -> println("Animal Not Found")
    }

This is how we use Kotlin when statement. You can compare the above 2 snippets of code and can easily decide which is more readable. This is much more powerful than if-else if you want to check for multiple conditions. If you know Java, this can be considered as a replacement for Switch Statement. 

Another Example - 

When a user registers on the site - possible scenarios can be coded as below - 
    val userStatus = registerUser(user) // some mechanism to register user

    when(userStatus)
    {
        "NEW" -> println("New user")
        "EXISTINGUSER" -> println("Email already exists")
        "INVALID" -> println("Incorrect Email or Password")    
    }

Kotlin When Expression

Just like if-else, when can be used as an expression i.e. result of the when expression can be assigned to a variable. Let's take the above example and write it as expression - 
    val animal = "Dog"

    val result = when(animal)
    {
    	"Cat" -> "Animal is Cat"
        "Dog" -> "Animal is Dog"
        "Horse" -> "Animal is Horse"
        else -> "Animal Not Found"
    }
    println(result)

Here you can see the result of when expression is stored in a result variable. It seems simple but very powerful way of writing conditional statements when you want to evaluate results based on multiple conditions. 

Let's take another example for when expression - 

val age = 14
val result = when(age)
{
    11 -> "Eleven"
    12 -> "Twelve"
    13..19 -> "Teenager"
}
println(result)

Here we have used the concept of range inside when. In simple words, it checks if the age lies between 13 & 19 then s/he is a teenager.

That's it for this article. For more articles on Kotlin Tutorials For Beginner Series - refer to this.

Happy Learning !! Cheers From CheezyCode.

Comments

Popular posts from this blog

Create Android Apps - Getting Started

Kotlin Type Checking and Smart Cast with Examples