Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Kotlin: when expression

‘when’ is equivalent to switch statement in Java.

Syntax
when(expression){
         1 -> {//Perform Something}
         2 -> {//Perform Something}
         else -> {//Perform something}
}

‘when’ evaluates the expression  against all the possible cases sequentially. If none of the case is satisfied, then else block will execute.

WhenDemo.kt
fun main(args: Array) {

var a : Int = 5

when(a){
12 -> println("Value 12 is checked")
5 -> println("Value 5 is checked")
3 -> println("Value 3 is checked")
else -> println("No value is checked")
}
}

Output
Value 5 is checked

You can combine multiple branch statements in when expression.


WhenDemo.kt
fun main(args: Array) {

var a : Int = 5

when(a){
2, 3, 5, 7 -> println("Prime number")
4, 6, 8 -> println("Even number other than 2")
else -> println("No value is checked")
}
}


Output
Prime number

You can also use arbitrary expressions as branch conditions. For example, I used 2+3 as branch condition.


WhenDemo.kt
fun main(args: Array) {

var a : Int = 5

when(a){
2+3 -> println("Checked value 5")
4, 6, 8 -> println("Even number other than 2")
else -> println("No value is checked")
}
}


Output
Checked value 5

You can also check the ranges (or) not in ranges in branch condition.


WhenDemo.kt

fun main(args: Array) {

var a : Int = 5

when(a){
in 1..5, in 11..15 -> println("a is in between 1 to 5 (or) 11 to 15")
in 6..10 -> println("a is in range of 6 to 10")
else -> println("x is not in range")
}
}

Output

a is in between 1 to 5 (or) 11 to 15



Previous                                                 Next                                                 Home


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Kotlin: when expression

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×