Kotlin Tutorial

Kotlin Classes

Kotlin when Expression

You also can use when instead of if..else; when is the conditional expression with multiple branches.

Normal usage of when:

Example:

WHY KOTLIN:

  • Kotlin is Easy to learn
  • Kotlin is Interoperable with Java and many other languages
  • Kotlin is Safe and Concise
  • Kotlin is more easier; If you already know Java
  • Kotlin is free to use

This tutorial will teach you the most basic fundamentals of Kotlin.
NOT REQUIRED, any prior programming language experience.

				
					when (days) {
   1 -> println("Sunday")
   2 -> println("Monday")
   3 -> println("Tuesday")
   //  . . . to 7 (Saturday)
   else -> {
       println("No day exists on that number")
   }  
}

				
			

Using when we match its argument (days) against all of its branches; and when some condition is satisfied that will print or perform a particular function.

The else branch is executed when none of the other conditions get satisfied.

Remember? : The when expression is similar to switch case statement. If you are familiar with Java or other C-like languages you may also be familiar with switch case statement.

Kotlin when as an expression:

Example:

				
					var month = 5
var result = 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 -> {
       "No month exists on that number"
   }
}
println("Month is $result"
				
			

The code above outputs:

Month is May

Same like the “if” expression; using when as an expression “else” is mandatory.

Learn more about when expression, visit Kotlin when expression.