Hi, I’m looking for a way around a compilation err...
# getting-started
m
Hi, I’m looking for a way around a compilation error when interacting with specific Java code. I have a preexisting Java code (in a library, which I cannot change and need to consume) the code like this
Copy code
class Foo<T extends Enum<T>> {
  Foo(Class<T> type) {}
}

enum FEnum {
  BLAH
}
and then I try to instantiate
Foo
in Kotlin
Copy code
fun main(args: Array<String>) {
    val foo = Foo(FEnum::class.java) // works ok, but have to hard-code enum class name here

    val type: Class<out Enum<*>> = FEnum::class.java
    val bar = Foo(type) // Error: doesn't work when class is obtained dynamically 
}
How can I modify the Kotlin code, passing
type
as some
Class
, so that
Foo
constructor accepts it?
a
inline fun <reified T: Enum<T>> createFoo() = Foo(T::class.java)
then you are able to create an instance with
createFoo<FEnum>()
m
@Andreas Sinz this works, but still requires me to hard code enum name here. But I need to pass it via a variable. There are many enums in my code, and the enum class name to use is saved in a file, which is later read into a variable of type
Class<....>
and enum values are iterated via reflection in
Foo
I cannot pass a variable
type
to code like
createFoo<type>()
… it wouldn’t compile
basically, if `Foo`s template were written as
T extends Enum
instead of
T extends Enum<T>
, then my Kotlin code with
Class<out Enum<*>>
would work I don’t understand how I can represent in Kotlin that it’s not just an
Enum
but
Enum
of
T
a
this is not possible on the JVM because of type erasure
m
so because of type erasure the code would work on Java (with unchecked cast, probably), but cannot be done at all on Kotlin, right?
a
If you can do it in java, you can do it the same way in kotlin