Is it possible to get a `Class<SomeEnumType>...
# announcements
b
Is it possible to get a
Class<SomeEnumType>
from a
KType
created elsewhere via
typeOf<SomeEnumType>()
? I feel like it should be possible, but I'm struggling to find the right call to get it.
z
KType.classifier as? KClass
1
b
Thanks (again!) Zach....I've gotta pass a type argument to
KClass
there, though, and all I could pass is
<*>
, no?
(Since I don't know what it is)
If I do
println(type.classifier as? KClass<*>)
It does print as the right type, but it assigns as
KClass<*>
b
as KClass<T>
☝️ 1
b
I don't have a
T
here, unfortunately, just the
KType
b
T meaning your type
z
as KClass<*>
if you don’t have the type
b
If the answer is I have to have a
T
, I might be able to work something out, but I wondered if I could get that from the
KType
z
the actual
classifier
will be the KClass of your enum type
b
The problem is I'm calling a method which is defined as
<T extends Enum<T>> T getEnum(Class<T> var1, String var2);
so I have to get a
Class<T>
with
<T extends Enum<T>>
I can do
type.isSubtypeOf(typeOf<Enum<*>>())
to check that it is an enum
z
as KClass<Enum<*>>
?
b
I tried that, but compiler still isn't happy
b
Buy it some roses, see if that makes it happy 😄
b
image.png
Ha..if only that worked 🙂
val c = (type.classifier as KClass<Enum<*>>).java
helps a little...
image.png
Maybe it would be better to create my own
getEnum
extension function for this class in Kotlin and do that. But now I'm even trying that and it's still eluding me. Is it possible given a
String
and a
KType
of an enum to create an instance of that enum using
valueOf(someString)
?
z
I think you can also get the java
Type
of a
KType
, maybe that would help?
b
I played with that a bit...I think the recursive nature of the Enum type bounds makes things a bit weird.
Because I can get an
Enum<*>
, but because of how Enum type bounds are set, it wants the boundary to be
T : Enum<Enum<T>>
and it complains that
Enum<*>
isn't a subtype of
Enum<Enum<*>>
d
Nothing
helps you:
ktype.classifier as KClass<Nothing>
b
Wow! I just tried that...had no idea
KClass<Nothing>
would satisfy
T : Enum<T>
...that's pretty slick
z
Oh neat, that makes sense –
Nothing
is the bottom type, so it is a subtype of every possible type.
b
Yeah that's awesome...I had all but given up on this scenario, but I can test that it is some enum type using the KType and now cast it with a "T" I need using
Nothing
.