官术网_书友最值得收藏!

Using the when expression

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 rule, use when if you have more than two conditions. Use if for simple checks.

主站蜘蛛池模板: 六盘水市| 定结县| 峨山| 昆山市| 兰考县| 兴安县| 张家界市| 成武县| 青川县| 永吉县| 左贡县| 石楼县| 临清市| 卓尼县| 饶河县| 黄陵县| 临泽县| 镇原县| 拜泉县| 高邮市| 上杭县| 西城区| 榆社县| 泾源县| 大邑县| 成安县| 六盘水市| 寻乌县| 宁波市| 故城县| 叙永县| 呼玛县| 庐江县| 团风县| 邢台县| 分宜县| 鲜城| 泰兴市| 扶余县| 阿克陶县| 团风县|