I have class
class GenericClass[+T] (var x: T) {}
When I try to compile it I get:
Error:(6, 33) covariant type T occurs in contravariant position in type T of value x_=
class GenericCellImm[+T] (var x: T) {
How to fix it? What is the problem reason?
Covariant generic type means that if you have classes
BaseandChildthat extendsBase, then in every context whereGenericClass[Base]is a correct type using an object of typeGenericClass[Child]will also be correct. As a rough approximation it means that if yourGenericClass[T]provides read-only API, you may make+Tcovariant because it is always safe to returnChildinstead ofBase. However this is not true if you have some writeable API in yourGenericClass[T]. Consider following code:This code is safe if
gcis really of typeGenericClass[Base]but if you letGenericClass[Child]there, you'll write a value of typeBaseto a field that is typed withChildand this breaks expected type safety. ConsiderAnd this is exactly why the compiler doesn't allow your code with covariance.
If you want get some real suggestion on how to fix it, you should describe the higher-level problem you are trying to solve. Without such a description it is really hard to guess whether just using
valinstead ofvaris what you need or whether you just need to remove covariance altogether or if you need a more complicated code.