Hello, World! I'm finding myself doing this a lot...
# announcements
b
Hello, World! I'm finding myself doing this a lot (especially with enums):
Copy code
val isStateXyz = xx.state in setOf(FOO, BAR, FOOBAR)
Is this idiomatic? Also, I think it may be a bit bad performance... So I was thinking of creating this:
Copy code
inline fun Any?.equalsAny(vararg objects: Any?): Boolean = objects.any { this == it }
and use it like this
val isStateXyz = xx.equalsAny(FOO, BAR, FOOBAR)
Is it a good idea or should I just keep using
in
? Thoughts?
a
imho the only problem with
in setOf(..)
is recreating the set each time. But in general I use
in
with
EnumSet
a lot, and then it’s just a bitmask check
m
for the
setof
case, i assume that you only have a finite number of
setof
to test against, so initialize those inside the enum and create helpermethods that returns booleans.
👍 1
b
@araqnid are you saying you do i
in EnumSet.of( ...
?
a
I try to cache the sets I want to check against in companion objects etc, so it’s that I do
in someSet
where
someSet
is an EnumSet
b
allright
well...... I guess I'll just keep
in
then
thanks for your input, all :)
a
yes, if the sets are static, then extension properties on the enum would look good
val SomeEnum.isStateXyz get() = this in xyzStates
👍 1
oh hey, I just discovered you can define extension properties as delegates:
Copy code
operator fun <T : Enum<T>> EnumSet<T>.getValue(owner: T, property: KProperty<*>): Boolean {
            return owner in this
        }
so then you can define:
Copy code
val SomeEnum.isStateXyz by EnumSet.of(FOO, BAR, FOOBAR)
👍 1
Today I Learned 🎉
b
wow, beautiful 🙂