https://kotlinlang.org logo
#getting-started
Title
# getting-started
k

Karlo Lozovina

02/25/2022, 7:33 PM
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

Rob Elliot

02/25/2022, 11:09 PM
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

Karlo Lozovina

02/26/2022, 12:59 AM
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

Paul Griffith

02/26/2022, 2:11 AM
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

Rob Elliot

02/26/2022, 9:29 AM
My preference would be an
operator fun invoke
on a companion object: https://pl.kotl.in/0pmoOuZ8C
👍 1
k

Karlo Lozovina

02/26/2022, 6:41 PM
@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! 😄