Question:
Will the following code compile?
class GenericCellMut[-T](var x:T)
If yes, why?
If not, why not, and how to make it compile?
It doesn't compile, of course. There are two questions left – why and what to change to compile.
I tried to read articles about co/contravariance, but I didn’t get anything for myself.
Answer:
As far as I know, Scala checks that all contravariant types occur only in argument positions, and all covariant types only occur in return value positions.
Your expression fails because the presence of the field x
implies that it can be obtained from this class, i.e. use in covariant position. Because of this, it will not help to make the x
field constant.
As I understand it, you want to make the cell mutable.
It's not very clear to me why a mutable cell with the contravariance property might be needed. The only thing I can suggest to make this example compile is to write the following code:
class GenericCellMut[+T](val x:T)
This will be an immutable cell with the covariance property ( I note that it now has a not very suitable name ). You can't make the field mutable, because that would require a method to set the value of x
, which in turn would require you to put the type T
in a contravariant position.
If you want to have a mutable cell, then you have to make it invariant:
class GenericCellMut[T](val x:T)