Eman
Eman

Reputation: 1315

create Flag Enum from int

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.

Upvotes: 1

Views: 577

Answers (1)

Tenfour04
Tenfour04

Reputation: 93609

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 }

Upvotes: 5

Related Questions