Contravariance rule in Scala

Question:

Will the following code compile?

class GenericCellMut[-T](var x:T)

If so, why?
If not, why, and how to make it compile?

It naturally doesn't compile. Two questions remain – why and what to change in order to compile.

I tried to read articles about co / contravariance, but I couldn't get anything out of it.

Answer:

As far as I know, Scala verifies that all contravariant types occur only at argument positions, and all covariant types occur at return value positions.

Your expression fails validation because the field x implies that it can be obtained from this class, i.e. use in covariant position. Because of this, it won't help to make the x field constant.


As I understand it, you want to make the cell mutable.

I'm not very clear about what a mutable cell with contravariance property might be for. The only thing I can suggest in order for this example to compile is to write the following code:

class GenericCellMut[+T](val x:T)

This will be an immutable cell with a covariance property ( note that it now has a not very suitable name ). You cannot make a field mutable, since this would require a method for setting the value of x , which, in turn, requires putting the type T in a contravariant position.

If you want to have a mutable cell, you have to make it invariant:

class GenericCellMut[T](val x:T)
Scroll to Top