Home > OS >  create Flag Enum from int
create Flag Enum from int

Time:10-28

I have an interesting situation, we have a settings database that store enum values as an int, the back end knows how to handle this but on our mobile app I'm struggle to figure how how to reproduce this.

currently I have the following:

enum class ProfileDisplayFlags(val number:Int)
{
    Address(0x01),
    PhoneNumber(0x02),
    Email(0x04),
    TwitterHandler(0x08),
    GithubUsername(0x10),
    Birthday(0x20)
}

for example, if I get the setting value from the database of 3, it should return on the app that I want to display Address & PhoneNumber.

I'm lost on how I can do this, I found a solution on finding a single value but I need to be able to get multiple back.

CodePudding user response:

Each flag value is a different unique bit set to one, so you can filter by which ones are not masked (bitwise AND) to zero by the given flags.

companion object {
    fun matchedValues(flags: Int): List<ProfileDisplayFlags> =
        values().filter { it.number and flags != 0 }
}

To convert back, you can use bitwise OR on all of them.

fun Iterable<ProfileDisplayFlags>.toFlags(): Int =
    fold(0) { acc, value -> acc or value.number }
  • Related