I have the following interface in kotlin, not modifiable because it's defined in a third party library. And I would like to override the generic method using a type parameter of the subclass:
interface Factory {
fun <T> create(modelClass: Class<T>): T
}
// The naive solution doesn't compile : "Class is not abstract and does not implement abstract member":
class ConcreteFactory1 <T> (val creator: () -> T) : Factory {
override fun create(modelClass: Class<T>): T {
return creator()
}
}
// If we introduce a second type parameter, it compiles, but generates a "Unchecked Cast" warning:
class ConcreteFactory2 <T> (val creator: () -> T) : Factory {
override fun <T2> create(modelClass: Class<T2>): T2 {
return creator() as T2
}
}
Is there a way to achieve this without compilation warning ?