Kotlin Flow Control : When/Switch Expression


When Expression in kotlin programming is language replaces the switch conditional operator of C-like languages. Kotlin “when” operator matches the variable value with the branch conditions. If the condition of branch matches with the value then it will execute the statement of that branch.

Example:
fun main(args: Array<String>) {
   val x:Int = 1
   when (x) {
      1 -> print("x = = 1")
      2 -> print("x = = 2")
      
      else -> { // Note the block
         print("x is neither 1 nor 2")
      }
   }
}
Output: x = = 1

Kotlin compiler matches the value of "x" with the given branches. If the value is not matching any of the branches, then it will execute the "else" part. Here "else" works similar to "DEFAULT" operator of C-like languages.

Kotlin provides multiple checks in the same line by providing “,” inside the checks.
fun main(args: Array<String>) {
   val x:Int = 3
   when (x) {
      1,2 -> print(" Value of X either 1,2")
      
      else -> { // Note the block
         print("x is neither 1 nor 2")
      }
   }
}

Output: x is neither 1 or 2

You can also check a value for a range:
fun main(args: Array<String>) {
   val x:Int = 5
   when (x) {
    in 1..10 -> print("x is in the range")
    else -> { print("none of the above")
     }
   }
 }
Output: x is in the range

Comments