The when Statement
Learn about when statement and enhance the code readability.
We'll cover the following...
The when
statement is an alternative to if
-else
-if
. In every branch, we specify a predicate and the body that should be executed if this predicate returns true
(and previous predicates did not). So, it works just like if
-else
-if
but should be preferred because its syntax is better suited for multiple conditions.
Press + to interact
fun main() {println("Is it going to rain?")val probability = 70when {probability < 40 -> {println("Na-ha")}probability <= 80 -> {println("Likely")}probability < 100 -> {println("Yes")}else -> {println("Holly Crab")}}}
Like in an if
statement, braces are needed only for bodies with more ...