In this tutorial you will learn about the Kotlin when Expression and its application with practical example.
Kotlin when Expression
In Kotlin, when expression is considered as replacement of switch statement exists in other languages like C, C++, and Java. It is more concise yet powerful than switch statements.
Syntax:-
1 2 3 4 5 6 7 8 9 |
when (expression){ value_1 -> // branch_1 statements value_2 -> // branch_2 statements value_3 -> // branch_3 statements … else -> // default statements } |
Using When as an Expression
In Kotlin, when can be used as an expression like the if and we can assign its result to a variable –
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
fun main(args: Array<String>){ var dayOfWeek = 5 var dayOfWeekInString = when(dayOfWeek) { 1 -> "Monday" 2 -> "Tuesday" 3 -> "Wednesday" 4 -> "Thursday" 5 -> "Friday" 6 -> "Saturday" 7 -> "Sunday" else -> "Invalid Day" } println("Today is $dayOfWeekInString") // Today is Friday } |
Output:-
1 |
Today is Friday |
Using when Without Expression
In the above example, we used when as an expression. However, it’s not mandatory to use when as an expression.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
fun main(args: Array<String>){ var dayOfWeek = 5 when(dayOfWeek) { 1 -> println("Today is Monday") 2 -> println("Today is Tuesday") 3 -> println("Today is Wednesday") 4 -> println("Today is Thursday") 5 -> println("Today is Friday") 6 -> println("Today is Saturday") 7 -> println("Today is Sunday") else -> println("Today is Invalid Day") } } |
Output:-
1 |
Today is Friday |
Multiple when branches into one
In Kotlin, multiple branches can be combined into one as comma separated. This is helpful when you need to run a common logic for multiple cases –
Example:-
1 2 3 4 5 6 7 8 9 10 |
fun main(args: Array<String>){ var dayOfWeek = 6 when(dayOfWeek) { 1, 2, 3, 4, 5 -> println("It a Weekday") 6, 7 -> println("Its Weekend") else -> println("Invalid Day") } } |
Output:-
1 |
Its Weekend |
Checking given value is in a range or not using in
operator
In Kotlin, range is indicated using the (..) operator. For example, you can create a range from 1 to 5 using 1..5. The in operator allows you to check if a value belongs to a range/collection –
Example:-
1 2 3 4 5 6 7 8 9 10 11 |
fun main(args: Array<String>){ var dayOfMonth = 5 when(dayOfMonth) { in 1..7 -> println("Its First Week of the Month") !in 15..21 -> println("Its Third week of the Month") else -> println("none of the above") } } |
Output:-
1 |
Its First Week of the Month |
Checking given variable is of certain type or not using is
operator
In Kotlin, is and !is operator can be used to check whether a value is of a particular type in runtime.
Example:-
1 2 3 4 5 6 7 8 9 10 11 12 |
fun main(args: Array<String>){ var x = 5 when(x) { is Int -> println("$x is an Integer") is String -> println("$x is a String") is Double -> println("$x is not Double") else -> println("none of the above") } } |
Output:-
1 |
5 is an Integer |