Code snippet
fun main() {
val myClass : AbsClass<Any> = MyClass()
// Error - type mismatch
val myClass : AbsClass<*> = MyClass()
// Not Error, but parameter of 'foo' is 'Nothing'
val myClass : AbsClass<Any> = MyClass() as AbsClass<Any>
// It's correct works with unchecked cast warning and unnecessary casting code.
myClass.foo(MyModel())
}
class MyClass() : AbsClass<MyModel>() {
}
abstract class AbsClass<T> {
fun foo(value:T){}
}
data class MyModel(val number:Int = 0)
Question
I want writing code as val myClass : AbsClass<Any> = MyClass() but, it shows type mismatch error. How to solve this problem(avoid type casting codeas AbsClass<Any>)?
foohasinsemantics. This only works if you can changeAbsClass<T>toAbsClass<out T>Foo<Derived>is-not-aFoo<Parent>. So you cannot assign aAbsClass<MyModel>instance to aAbsClass<Any>reference.fun foo(value:T){}IDE will complain sayingType parameter T is declared as 'out' but occurs in 'in' position in type T AbsClass<out T>