How to implement switch-case statement in Kotlin?


Switch case statement in any programming language is a type of selection control mechanism that allows the developers to test the value of a variable or expression and change the control flow of a program based on the outcome of the comparison. It also provides an option to do something whenever the value of the variable does not match a given value.

Kotlin does not provide an option to write a switch-case statement; however we can implement the switch-case functionality in Kotlin using the when() function which works exactly the same way switch works in other programming languages.

In this article, we will take a simple example and demonstrate how we can implement the switch-case functionality Kotlin.

Example – Implementing Switch-Case using when()

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

fun main(args: Array<String>) {
   // generating a random value 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 -> {
         print("x is neither 1 nor 2")
      }
   }
}

Output

The output may vary based on the random value generated.

Current value: 10 
randomVal == 10

Updated on: 16-Mar-2022

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements