Created
October 21, 2021 11:14
-
-
Save sergeyzenchenko/ebb36947006fb4490c4f81ced8a3d2bc to your computer and use it in GitHub Desktop.
Kotlin reified generics issue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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