- Functional Kotlin
- Mario Arias Rivu Chakraborty
- 257字
- 2021-06-24 19:15:25
Enum
Enum in Kotlin is a way to define a set of constant values. Enums are very useful, but not limited, as configuration values:
enum class Flour {
WHEAT, CORN, CASSAVA
}
Each element is an object that extends the Flour class.
Like any object, they can extend interfaces:
interface Exotic {
fun isExotic(): Boolean
}
enum class Flour : Exotic {
WHEAT {
override fun isExotic(): Boolean {
return false
}
},
CORN {
override fun isExotic(): Boolean {
return false
}
},
CASSAVA {
override fun isExotic(): Boolean {
return true
}
}
}
Enum can also have abstract methods:
enum class Flour: Exotic {
WHEAT {
override fun isGlutenFree(): Boolean {
return false
}
override fun isExotic(): Boolean {
return false
}
},
CORN {
override fun isGlutenFree(): Boolean {
return true
}
override fun isExotic(): Boolean {
return false
}
},
CASSAVA {
override fun isGlutenFree(): Boolean {
return true
}
override fun isExotic(): Boolean {
return true
}
};
abstract fun isGlutenFree(): Boolean
}
Any method definition must be declared after the (;) separating the last element.
When enums are used with when expressions, Kotlin's compiler checks that all cases are covered (individually or with an else):
fun flourDescription(flour: Flour): String {
return when(flour) { // error
Flour.CASSAVA -> "A very exotic flavour"
}
}
In this case, we're only checking for CASSAVA and not the other elements; therefore, it fails:
fun flourDescription(flour: Flour): String {
return when(flour) {
Flour.CASSAVA -> "A very exotic flavour"
else -> "Boring"
}
}
推薦閱讀
- Embedded Linux Projects Using Yocto Project Cookbook
- Spring技術內幕:深入解析Spring架構與設計
- VMware vSphere 6.7虛擬化架構實戰指南
- jQuery炫酷應用實例集錦
- D3.js By Example
- Spring Boot+MVC實戰指南
- 編程可以很簡單
- Illustrator CS6設計與應用任務教程
- Mastering Elixir
- Java EE 7 with GlassFish 4 Application Server
- HTML5移動前端開發基礎與實戰(微課版)
- Visual C++程序設計與項目實踐
- Mastering Drupal 8
- Java Script從入門到精通(第5版)
- C++從零開始學(視頻教學版)(第2版)