August 2017
Intermediate to advanced
440 pages
10h
English
The when expression in Kotlin is a multiway branch statement. The when expression is designed as a more powerful replacement for the Java switch... case statement. The when statement often provides a better alternative than a large series of if... else if statements, as it provides more concise syntax. Let's look at an example:
when (x) {
1 -> print("x == 1")
2 -> print("x == 2")
else -> println("x is neither 1 nor 2")
}
The when expression matches its argument against all branches one after another until the condition of some branch is satisfied. This behavior is similar to Java's switch... case, but we do not have to write a redundant break statement after every branch.
Similar to the if clause, we can use when either ...
Read now
Unlock full access