The when expression in Kotlin works same as switch case in other programming languages such as C, C++ and Java.
Kotlin when expression simple example
/** * created by Chaitanya for Beginnersbook.com */ package beginnersbook fun main(args : Array<String>){ var ch = 'A' when(ch){ 'A' -> println("A is a Vowel") 'E' -> println("E is a Vowel") 'I' -> println("I is a Vowel") 'O' -> println("O is a Vowel") 'U' -> println("U is a Vowel") else -> println("$ch is a Consonant") } }
Output:
A is a Vowel
We can also rewrite the same code in a more cleaner way like this:
/** * created by Chaitanya for Beginnersbook.com */ package beginnersbook fun main(args : Array<String>){ var ch = 'A' when(ch){ 'A', 'E', 'I', 'O', 'U' -> println("$ch is a Vowel") else -> println("$ch is a Consonant") } }
Kotlin when expression with ranges
We can also use ranges in when expression. In the following example we have used multiple ranges inside the when expression to find out the digits in the given number.
/** * created by Chaitanya for Beginnersbook.com */ package beginnersbook fun main(args : Array<String>){ var num = 78 when(num) { in 1..9 -> println("$num is a single digit number") in 10..99 -> println("$num is a two digit number") in 100..999 -> println("$num is a three digit number") else -> println("$num has more than three digits") } }
Output:
Arithmetic operation inside when expression
We can also perform operations on the variable that we pass in the when expression.
/** * created by Chaitanya for Beginnersbook.com */ package beginnersbook fun main(args : Array<String>){ var age = 16 when(age) { in 1..17 -> { val num = 18 - age println("You will be eligible for voting in $num years") } in 18..100 -> println("You are eligible for voting") } }
Output:
Leave a Reply