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

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.

主站蜘蛛池模板: 大田县| 屯留县| 应用必备| 东海县| 永春县| 高雄市| 丹棱县| 长兴县| 中卫市| 嵩明县| 宁南县| 泉州市| 威宁| 彭泽县| 葵青区| 舒城县| 梓潼县| 伊金霍洛旗| 托克托县| 班戈县| 张北县| 江津市| 黄龙县| 青州市| 冷水江市| 涿州市| 辉南县| 建宁县| 岢岚县| 班玛县| 泉州市| 双鸭山市| 澄江县| 玛多县| 平凉市| 新泰市| 嘉善县| 合川市| 安平县| 松潘县| 淮安市|