Left Index

Kotlin When Expression

In Kotlin, when you want to choose any one option among many then we use when expression. Like java there is switch expression, kotlin replace switch with when. Let's see syntax of when expression:

package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	var num1 = 12

	var msg = when(num1) {
		10 -> "It's ten"
		11 -> "It's elevan"
		12 -> "It's twelve"
		13 -> "It's thirtheen"
		14 -> "It's fourtheen"
		else -> "No number selected"
	}
	
	println(msg)
}


Multiple Statement of when Using Braces(Block)

package com.theitbulls.kotlinex

fun main(args: Array<String>) {
	var num1 = 10

	when(num1) {
		10 -> {
			println("It's ten")
			println("Your choice is good")
		}
		11 -> println("It's elevan")
		12 -> println("It's twelve")
		13 -> println("It's thirtheen")
		14 -> println("It's fourtheen")
		else -> println("No number selected")
	}
}