- Hands-On Design Patterns with Kotlin
- Alexey Soshin
- 158字
- 2021-06-25 20:49:24
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.
推薦閱讀
- Vue.js 3.x快速入門
- Apache ZooKeeper Essentials
- 算法大爆炸:面試通關步步為營
- 編寫整潔的Python代碼(第2版)
- 云原生Spring實戰
- Practical Windows Forensics
- Troubleshooting PostgreSQL
- 精通Python設計模式(第2版)
- Linux命令行與shell腳本編程大全(第4版)
- Learning Concurrency in Kotlin
- Vue.js應用測試
- Vue.js 3應用開發與核心源碼解析
- OpenCV 3計算機視覺:Python語言實現(原書第2版)
- C++程序設計教程
- After Effects CC案例設計與經典插件(視頻教學版)