When operator in Kotlin

In this tutorial, we will learn about when operator in Kotlin. When operator is work same as Switch statement of Java. In Kotlin when operator uses to match an argument with all the branches until it finds a satisfying condition in a branch. After finding satisfying condition it runs all statements inside the scope of that branch. Follow the given example to understand when operator.

Example Program:

fun main(args: Array<String>) {
   val num:Int = 2
   when (num) {
      1 -> print("num is = 1")
      2 -> print("num is = 2")
      else -> {
         print("Out of range")
      }
   }
}

We when operator we can combine multiple branches using comma. check the following example.

Example Program:

fun main(args: Array<String>) {
   val num:Int = 8
   when (num) {
      1,2,3,4,5 -> print("num is in first range")
      6,7,8,9,10 -> print("num is in second range")
      else -> {
         print("Out of range")
      }
   }

We can also use in to check the particular value in a range or not.

Example Program:

fun main(args: Array<String>) {
   val num:Int = 12
   when (num) {
      in 1..10 -> print("num is in first range")
      in 10..20 -> print("num is in second range")
      else -> {
         print("Out of range")
      }
   }
}

 

Spread the love
Scroll to Top
×