Kotlin 'when' statement vs Java 'switch'


Switch-case statement in any programming language allows the programmers to testify it against different values. It also provides an option to do something whenever the value of the variable does not match with a given value. In this article, we will take a simple example and demonstrate how we can implement the switch-case statement in Kotlin.

Kotlin does not provide any option to write a switch-case statement. However, Kotlin provides an option to implement when() which works exactly the same way switch works in other programming languages.

Example – Implementing switch-case in Java

In this example, we will implement switch-case in Java.

public class MyExample {
   public static void main(String[] args) {
      int number=10;
      switch(number){

         case 10: System.out.println("Input was 10");
         break;

         case 20: System.out.println("Input was 20");
         break;

         case 30: System.out.println("Input was 30");
         break;

         // Default case statement
         default:System.out.println("Input was not 10, 20 or 30");
      }
   }
}

Output

It will produce the following output −

Input was 10

Example - Implementing switch-case using when()

In this example, we will generate a random value and we will be using when() to perform different operations on the variable.

fun main(args: Array<String>) {

   // generating random value for our variable between (0 to 10).
   var randomVal=(0..10).random()

   println("Current value: " + randomVal)

   when (randomVal) {
      1 -> print("randomVal == 1")
      2 -> print("randomVal == 2")
      3 -> print("randomVal == 3")
      4 -> print("randomVal == 4")
      5 -> print("randomVal == 5")
      6 -> print("randomVal == 6")
      7 -> print("randomVal == 7")
      8 -> print("randomVal == 8")
      9 -> print("randomVal == 9")
      10 -> print("randomVal == 10")

      else -> { // Note the block
         print("x is neither 1 nor 2")
      }
   }
}

Output

On execution, it will generate a random value in between 1 to 10.

Current value: 7
randomVal == 7

Updated on: 01-Mar-2022

620 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements