- Kotlin Standard Library Cookbook
- Samuel Urbanowicz
- 166字
- 2021-07-23 19:05:50
There's more...
Range expressions can enhance use of the when expression as well. In the following example, we are going to implement a simple function that will be responsible for mapping a student's exam score to a corresponding grade. Let's say we have the following enum class model for student grades:
enum class Grade { A, B, C, D }
We can define a function that will map the exam score value, in the 0 to 100 % range, to the proper grade (A, B, C, or D) using a when expression, as follows:
fun computeGrade(score: Int): Grade =
when (score) {
in 90..100 -> Grade.A
in 75 until 90 -> Grade.B
in 60 until 75 -> Grade.C
in 0 until 60 -> Grade.D
else -> throw IllegalStateException("Wrong score value!")
}
Using ranges together with the in operator makes the implementation of the computeGrade() function much cleaner and more natural than the classic equivalent implementation using traditional comparison operators, such as <, >, <=, and >=.
推薦閱讀
- Dynamics 365 for Finance and Operations Development Cookbook(Fourth Edition)
- Linux C/C++服務器開發實踐
- Java應用開發與實踐
- HTML5+CSS3基礎開發教程(第2版)
- Rust Essentials(Second Edition)
- Scientific Computing with Scala
- Hands-On Natural Language Processing with Python
- 智能手機故障檢測與維修從入門到精通
- 深入淺出Python數據分析
- 寫給青少年的人工智能(Python版·微課視頻版)
- SQL Server 2012 數據庫應用教程(第3版)
- Spring Boot從入門到實戰
- 開源網絡地圖可視化:基于Leaflet的在線地圖開發
- Python程序設計
- Expert Angular