Replace Switch with When in Kotlin

 Replace Switch with When in Kotlin

Replace Switch with When in Kotlin

In this blog, we will look upon the replacement of switch with the when keyword. Firstly, we will look on to some examples of switch and after that, we will look at how the when keyword makes our task or code easier and more understandable. So, let’s get started.

Switch

If we are using some conditional statements and the condition used in the conditional statements are applied on similar type of data, then instead of having a vast or big code for the conditional statement, we can use switch to avoid using so many conditional statements in our code.

For example: below is an example of a conditional statement used to print the word representation of numbers:

                             
                    if (number == 1) {
                        System.out.println("One");
                    } else if (number == 2) {
                        System.out.println("Two")
                        } else if (number == 3) {
                        System.out.println("Three")
                        } else {
                        System.out.println("Number is not between 1 and 3")
                        }
                    
                             
                         

So, in the above code in order to print the numbers in word, you have to use various conditional statements and this results in a large number of lines of code. Think of a situation when you have to print the words representation of numbers up to 100 or 1000. If you are using conditional statements then you have to use 1000 conditional statements.

To remove this difficulty, switch-case was introduced, where we pass the variable to be compared with-in the switch statement (in our example, that variable is number) and compare it with various case statements present corresponding to it and do the operation. So, the switch-case version of the above code will be:

                               
                    switch(number) {
                        case 1:
                            System.out.println("One");
                            break;
                        case 2:
                            System.out.println("Two");
                            break;
                        case 3:
                            System.out.println("Three");
                            break;
                        default:
                            System.out.println("Number is not between 1 and 3");
                            break;
                    }
                                
                       
                           

In the above code, number is passed in switch statement and cases are used to compare that number. For example, if the number is 1 then case 1 will be executed, if number is 2 then case 2 will be executed and so on. But if the number is not equal to any of the case present then the default block will be executed.

This is a very convenient way of using conditional statements. But many programming languages like Python doesn’t use the switch-case. They have some different and better way of using the conditional statements except switch. In Kotlin we use when in place of switch. So, let’s move on and try to find how we can replace switch with when?

when

So, if you are moving from Java to Kotlin, then you will find some changes in the syntax part also. In Java we use switch but in Kotlin, that switch gets converted to when. when is also used for conditional representation but it does the things in a very smarter and easier way. Whenever you are having a number of possibilities then you can use when in your code.

For example, the above code that was written using switch gets converted to something like below after using when:

                               
                                when(number) {
                                    1 -> println("One")
                                    2 -> println("Two")
                                    3 -> println("Three")
                                    else -> println("Number is not between 1 and 3")
                                }
                            
                           

In the above code, like in switch, the number is passed in when and then we compare that number with various options available. In our case, if the number == 1, then “one” will be printed and so on. If more than one match is found then the match that occurs first will be considered only. If no match to the number is found then the else part will be executed.

Also, there is no need of that else part if you are sure that your code will never code to the else part in any situation. For example:

                               
                    val noElseChecking = true

                    when(noElseChecking) {
                        true -> println("The value is true")
                        false -> println("The value is false")
                    }
                    
                               
                           

More features of when

Till now, we have a basic idea of how when can be used to replace switch in Kotlin. Let’s look upon some more features of when that makes it a good to have in any Kotlin code:

  • • Two or more choices: While using the switch statement, we can check or compare with the value passed in switch in one case at a time, but in when we can apply more than one choice. For example:
  •                                
                            •	when(number) {
                            •	    1 -> println("One")
                            •	    2, 3 -> println("Two or Three")
                            •	    4 -> println("Four")
                            •	    else -> println("Number is not between 1 and 4")
                            •	}
                             
                               

    In the above example, the second statement says that if the value of number will be 2 or 3 then the code will print “Two or Three”. Here we are having more than one choice.

  • • Condition branch: You can apply conditions in any branch of when statement and the body of that statement will only be executed when the condition is satisfied. For example:
  •                                
                        •	when(number) {
                        •	    1 -> println("One") //statement 1
                        •	    2 -> println("Two") //statement 2
                        •	    3 -> println("Three") //statement 3
                        •	    in 4..8 -> println("Number between 4 and 8") //statement 4
                        •	    !in 9..12 -> println("Number not in between 9 and 12") //statement 5
                        •	    else -> println("Number is not between 1 and 8") //statement 6
                        •	}
                                        
                                   
                               

    In the above example, if you pass number == 6 then the output will be “Number between 4 and 8”. But there is one doubt, as the number is 6 then statement 4 and 5 are true then why only statement 4 is executed?

    The reason behind this is, if more than two statements are correct then the statement appeared first will be used and other true statements will be discarded.

    Conclusion

    In this blog, we learned how to use when in place of switch in Kotlin. We saw that, if we are having a number of possibilities for a particular variable then we can make use of when to handle all the possibilities. Also, we can use when for multiple or more than one choices.

    That’s it for this blog! Keep Exploring

    I Hope you enjoy this blog

    Thank You

    Want a Team that Delivers Result ? Connect now with us.

    -

    Our Offices

    INDIA

    F-429, Phase 8B, Industrial Area, SAS Nagar, Punjab 160059

    +91 82198-18163

    USA

    13506 Summerport Village Pky Suite 355 Windermere, FL 34786

    +1 (321) 900-0079

    CANADA

    15 Meltwater Cres, Brampton L6P3V8

    +1 (647) 892-6147