我有以下代码
enum class State {
EMPTY, LOADING, DATA, ERROR
}
private var currentState = State.EMPTY
private var timer: Timer? = null
fun startTimer() {
if (timer == null) {
timer = fixedRateTimer(period = 1000, action = {
mainvView.showView(currentState)
currentState = when (currentState) {
State.EMPTY -> State.LOADING
State.LOADING -> State.DATA
State.DATA -> State.ERROR
State.ERROR -> State.EMPTY
}
})
}
}
以1s的固定间隔迭代枚举。
我不是特别喜欢这件作品
currentState = when (currentState) {
State.EMPTY -> State.LOADING
State.LOADING -> State.DATA
State.DATA -> State.ERROR
State.ERROR -> State.EMPTY
}
因为我希望更多地采用下面的内容,所以我不需要明确写出所有的状态转换
if (currentState == State.ERROR) {
currentState = State.EMPTY
} else {
currentState++
}
显然currentState++
是不可能的。还有其他方法吗?
答案 0 :(得分:4)
如果您使用像
这样的运算符重载,则可以执行currentState++
之类的操作
operator fun State.inc(): State = when(this){
State.EMPTY -> State.LOADING
State.LOADING -> State.DATA
State.DATA -> State.ERROR
State.ERROR -> State.EMPTY
}
或者只是想圈出枚举
operator fun State.inc(): State {
val size = State.values().size
return State.values()[(this.ordinal + 1) % size]
}
答案 1 :(得分:0)
您可以使用通用功能
inline operator fun <reified E : Enum<E>> E.inc() =
enumValues<E>()[(ordinal + 1) % enumValues<E>().size]