Replace Switch with When in Kotlin

Replace Switch with When in Kotlin

Hello World! If you are reading this blog, then you must be a programmer and you know how to code in particular programming language. I mean to say that you must be familiar with at least one of the programming languages and know about the basics syntax and elements used in any programming languages like conditional statements, looping structures, functions, etc.

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

In the above example, the variable noElseChecking is assigned true. After that, we are checking that variable in when block. The idea here is that either the value of the noElseChecking variable will be true or false and there is no third case. So, if we handle these two case then there is no need of else part in when because if we use else then that code will be unreachable code.

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? If you are reading this blog with full concentration then you know the reason behind this because it is discussed in the introduction to when section. 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.

  • "when" without arguments: You can use when without any argument also i.e. simply write when and in the block or body of the when write some conditional statement. A when without an argument is like applying some conditional statements. For example:
when {
    number < 1 -> print("Number is less than 1")
    number > 1 -> print("Number is greater than 1")
}

In the above example, there is no argument passed in when, so, you can use conditional statement inside when by using the variables used in the code.

  • Any type passed in "when": You can pass any type of variable in when i.e. you can pass integer or string or character in when at a time. This facility was not there in switch, there if you are passing an integer value then your case must be an integer value otherwise you will get an error. But when you can use any type as below:
fun describe(obj: Any): String =
    when (obj) {
      1 -> "One"
      "Hello" -> "Greeting"
      is Long -> "Long"
      !is String -> "Not a string"
      else -> "Unknown"
    }

In the above example, the same object obj is used to compare with the integer value, then with the string value then it is checked for long and so on.

  • Smart casting: You can perform smart casting i.e. automatic casting if you are using an is expression in your when block. For example:
when (x) {
    is Int -> print("X is integer")
    is String -> print("X is string")
}

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!

Team MindOrks!