June 2018
Intermediate to advanced
310 pages
6h 32m
English
What if (no pun intended) we want to have more conditions in our if statement?
In Java, we use the switch statement. In Kotlin, there's a when expression, which is a lot more powerful, since it can embed some other Kotlin features.
Let's create a method that's based on the amount of money that will give cause to suggest a nice birthday gift:
fun suggestGift(amount : Int) : String { return when (amount) { in (0..10) -> "a book" in (10..100) -> "a guitar" else -> if (amount < 0) "no gift" else "anything!" }}
As you can see, when also supports a range of values. The default case is covered by the else block. In the following examples, we will elaborate on even more powerful ways to use this expression.
As a general ...
Read now
Unlock full access