When

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 -> println("Number is 1")
2,3,4,5 -> println("Number is in range from 2 to 5")
}
}

If you are using when as an expression, then it has to be exhaustive, that is, the compiler has to be sure that all possible branches are covered, as you can see in this example:

fun checkNumbersExhaustive(num: Int): String {
return when(num) {
1 -> "Number is 1"
2,3,4,5 -> "Number is in range from 2 to 5"
else -> "Number is higher than 5"
}
}

when accepts any object as its argument, unlike Java’s switch, which accepts only enums, strings and numbers. Here you can see how when can be used for type checking:

fun whenAny(any: Any) {
when (any) {
is Int -> println("This is an Int type")
is Double -> println("This is a Double type")
is String -> println("This is a String type")
}
}

You can also use when without arguments. You can test against arbitrary boolean conditions inside it. Consider the following example:

fun whenWithoutArgument(a: Int, b: Int) {
when {
a * b > 100 -> println("product of a and b is more than 100")
a + b > 100 -> println("sum of a and b is more than 100")
a < b -> println("a is less than b")
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.200.78