Skip to content

Instantly share code, notes, and snippets.

@sergeyzenchenko
Created October 21, 2021 11:14
Show Gist options
  • Save sergeyzenchenko/ebb36947006fb4490c4f81ced8a3d2bc to your computer and use it in GitHub Desktop.
Save sergeyzenchenko/ebb36947006fb4490c4f81ced8a3d2bc to your computer and use it in GitHub Desktop.
Kotlin reified generics issue
open class A {
}
open class B {
}
class Factory<R>(val mapper: () -> R) {
}
inline fun <reified T> factory(): Factory<T> {
return Factory(::createA)
}
inline fun <reified T: A> factoryWithConstrain(): Factory<T> {
return Factory(::createA)
}
inline fun <reified T: A> createA(): T {
return T::class.java.getDeclaredConstructor().newInstance()
}
inline fun <reified T: B> createB(): T {
return T::class.java.getDeclaredConstructor().newInstance()
}
fun main() {
val container: Factory<A> = factory()
println("result: ${container.mapper()}") // class java.lang.Object cannot be cast to class A (java.lang.Object is in module java.base of loader 'bootstrap'; A is in unnamed module of loader 'app')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment