Kotlin - when Expression Example

Kotlin’s when expression is the replacement of switch statement from other languages like C, C++, and Java. It is concise and more powerful than switch statements.

Kotlin - When Expression Examples

Using when as an Expression

Let's see a simple example of when expression:
package net.javaguides.kotlin fun main(args: Array < String > ) { // Using when as an Expression var month = 8; var monthString = when(month) { 1 - > "January" 2 - > "February" 3 - > "March" 4 - > "April" 5 - > "May" 6 - > "June" 7 - > "July" 8 - > "August" 9 - > "September" 10 - > "October" 11 - > "November" 12 - > "December" else - > "Invalid Month" } println(monthString); }
Output:
August

Using when Without Expression


It is not mandatory to use when as an expression, it can be used as normally as it used in other languages. For example:
package net.javaguides.kotlin fun main(args: Array < String > ) { // Using when Without Expression var dayOfWeek = 4 when(dayOfWeek) { 1 - > println("Monday") 2 - > println("Tuesday") 3 - > println("Wednesday") 4 - > println("Thursday") 5 - > println("Friday") 6 - > println("Saturday") 7 - > println("Sunday") else - > println("Invalid Day") } }
Output:
Thursday

Multiple Statement of when Using Braces

We can use multiple statements enclosed within a block of condition. For example:
package net.javaguides.kotlin fun main(args: Array < String > ) { var number = 1 when(number) { 1 - > { println("Monday") println("First day of the week") } 7 - > println("Sunday") else - > println("Other days") } }
Output:
Monday First day of the week



Comments