August 2018
Beginner
178 pages
4h 56m
English
Kotlin doesn’t have switch statements, like Java and other popular languages. Switch in other languages is a conditional operator which can be used for comparing multiple conditions on a variable.
In Kotlin this operator is called when and does the same job as a switch in other languages.
It checks the variable value against multiple conditions, and, if a condition is satisfied, it executes the expression for that branch. when is a lot more powerful than Java’s switch operator. when in Kotlin is an expression, which means it can also return values.
If when is used as a statement, then it doesn’t have to be exhaustive, that is, not all branches have to be covered, as this example shows:
fun checkNumbers(num: Int) { when(num) { 1 ->
Read now
Unlock full access