在下面的代码中,我试图将int位标志转换为枚举,但是没有得到正确的结果。
enum class State {
NONE = 0,
FORWARD =4,
BACKWARD =5,
}
infix fun Int.withFlag(flag: Int) = this or flag
fun fromInt(value: Int) = values().mapNotNull {
if (it.value.withFlag(value) == value ) it else null
}
// backward
val flag = 5
State.fromInt(flag)
// results NONE, FORWARD, BACKWARD
// expected BACKWARD
答案 0 :(得分:0)
类似这样的东西:
enum class State(val value: Int) {
NONE(0),
FORWARD(4),
BACKWARD(5);
companion object {
fun getByVal(arg: Int) : State? = values().firstOrNull { it.value == arg }
}
}
State.getByVal(5) //BACKWARD
State.getByVal(7) //null