How do you deal with "flag" enums in Kotlin? Let's...
# announcements
s
How do you deal with "flag" enums in Kotlin? Let's say I have flags 1,2,4,8 in my enum and from parsing some data, I obtain 5 (1 and 4 combined). How do I convert that 5 back into some enum value? In .NET, you have these "flag" enums and they are quite useful.
t
In kotlin this isn't implemented, I think. I use my own implementation.
ValuedEnum
holds current flag number.
IValued
represents enum entry with flag. As in C# you can intersect, union, etc it. https://github.com/ITesserakt/diskordin/blob/master/src/main/kotlin/org/tesserakt/diskordin/util/enums/IValued.kt https://github.com/ITesserakt/diskordin/blob/master/src/main/kotlin/org/tesserakt/diskordin/util/enums/ValuedEnum.kt
a
Use an
EnumSet
?
👌 1
☝️ 1
t
Enum set doesn't allows to clearly add one flags to another flags and also it is very easy to confuse flag codes, add non-flag enum to normal enum,
a
Not sure how it's easy to confuse flag codes if the whole point is you don't use any codes Except for the parsing,writing I guess, but you should only want to do that at most one place (if you really need to save bytes or w/e) Also "add non-flag enum to normal enum" sounds like you shouldn't mix different types of enums? The EnumSet is generic and thus can only contain enum instances of a certain type
t
I'm sure with you. In general cases it isn't quite useful. But ye, there are situations when flags explicitly being. It is some API (discord 😄), low-system mechanics, etc.
s
Is EnumSet multiplatform though? I skimmed through it, but it looked like it was Android specific.
t
It's java specific class
m
I would go with
EnumSet
too, otherwise you can try Java
BitSet
202 Views