Is there a way to call <EnumSet.noneOf()> given on...
# getting-started
k
Is there a way to call EnumSet.noneOf() given only a generic type parameter, let's say T? Neither
noneOf(T::class.java)
,
noneOf(T::class)
work. If I pass around a value, then everything works fine (
noneOf(value::class.java)
), but is there a way to keep everything on the type level?
r
You could use a reified function:
inline fun <reified T : Enum<T>> noneOf(): EnumSet<T> = EnumSet.noneOf(T::class.java)
val x = noneOf<MyEnum>()
k
Thanks, figured that one in the end. But still, I'd like to use it as a class property, and there are no reified classes...
I ended up just passing an extra value to the class, no big deal, just wondered if it could be done without it
p
If you just care about use-site convenience and don’t mind squinting a bit, you could have a “constructor” function for your class that’s actually
inline reified
- if you give it the same name as the class you can use it transparently https://pl.kotl.in/MF7-JYB83
r
My preference would be an
operator fun invoke
on a companion object: https://pl.kotl.in/0pmoOuZ8C
👍 1
k
@Rob Elliot wow, that's pretty cute & clever! didn't know I could overload the
invoke
operator 😄. Maybe a bit too clever, but it's a small codebase, why not go wild a bit! 😄