【Kotlin】enum class
宣告1: 最基礎的 neum 使用逗號分開
enum class Direction {
NORTH, SOUTH, WEST, EAST
}
通常搭配when做狀態或是類型判斷
when(direction){
Direction.NORTH -> // todo
Direction.SOUTH -> // todo
Direction.WEST -> // todo
Direction.EAST -> // todo
}
宣告2: 可輸入參數,並加入companion object function
常數(參數..), 常數(參數..) 使用逗號分割,最後一個使用分號區隔下方區塊
可加入 companion object function 增加使用靈活度
enum class EDeviceType(val id: String, val label: String) {
ANDROID("0", "安卓"),
IOS("1", "iOS");
companion object {
fun sortedList(desc: Boolean): List<EDeviceType> {
return if (desc) {
entries.sortedByDescending { it.id }
} else {
entries.sortedBy { it.id }
}
}
fun ofId(id: String): EDeviceType? {
return entries.firstOrNull { it.id == id }
}
}
}
enum class EUpdateType(val id: String, val label: String) {
NO_UPDATE("0", "不更新"),
FORCE_UPDATE("1", "強迫更新"),
RECOMMEND_UPDATE("2", "建議更新");
companion object {
fun sortedList(desc: Boolean): List<EUpdateType> {
return if (desc) {
entries.sortedByDescending { it.id }
} else {
entries.sortedBy { it.id }
}
}
fun ofId(id: String): EUpdateType? {
return entries.firstOrNull { it.id == id }
}
}
}
// 強迫更新的版號
val forceUpdateVersions = updateVersions.filter {
EUpdateType.ofId(it.updateType.orEmpty()) == EUpdateType.FORCE_UPDATE
}
枚舉常數可以使用相應的方法以及重寫的基底方法來聲明自己的匿名類別。
enum class ProtocolState {
WAITING {
override fun signal() = TALKING
},
TALKING {
override fun signal() = WAITING
};
abstract fun signal(): ProtocolState
}
fun main() {
var currentState: ProtocolState = ProtocolState.WAITING
println("Current state: $currentState")
currentState = currentState.signal()
println("Signal received, new state: $currentState")
currentState = currentState.signal()
println("Signal received, new state: $currentState")
}
// Current state: WAITING
// Signal received, new state: TALKING
// Signal received, new state: WAITING