枚举的位标志没有得到正确的结果



在下面的代码中,我试图将int位标志转换为enum,但没有得到正确的结果。

枚举标志

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

可能是这样的东西:

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

最新更新