0

In the below code, i'm trying to convert int bit flags to enum, but I'm not getting the right results.

Enum Flags

enum class State {
    NONE = 0,
    FORWARD =4,
    BACKWARD =5, 
}  

Bit Flag and conversion

 infix fun Int.withFlag(flag: Int) = this or flag
    fun fromInt(value: Int) = values().mapNotNull {
        if (it.value.withFlag(value) == value ) it else null 
    }

Action

 // backward
    val flag = 5
    State.fromInt(flag) 

Results

// results  NONE, FORWARD, BACKWARD
// expected BACKWARD

1 Answers1

0

Something like this maybe:

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
Sourav 'Abhi' Mitra
  • 2,390
  • 16
  • 15
  • I also need to support multiple bit exaple `println( State.getByVal(9) )//BACKWARD and FORWARD` – Ron June Lopez Apr 07 '20 at 09:39
  • Sure, please change the `getByVal()` implementation to suit your needs. Also change the return type to be `List`?. So in the given example how does `9` mean `Backward` and `Forward`? Some more examples would help. Could not make that out from the question itself. – Sourav 'Abhi' Mitra Apr 07 '20 at 15:56