Jay Taylor's notes
back to listing indexgenerics - Scala covariance / contravariance question - Stack Overflow
[web search]
Following on from this question, can someone explain the following in Scala:
I understand the distinction between
EDIT - now got this down to the following:
this is all good, but I now have two type parameters, where I only want one. I'll re-ask the question thus: How can I write an immutable EDIT 2: Duh! I used
| |||||||||||||||
| |||||||||||||||
Generically, a covariant type parameter is one which is allowed to vary down as the class is subtyped (alternatively, vary with subtyping, hence the "co-" prefix). More concretely:
We just assigned a value of type Note that there is another type of variance known as contravariance. This is very important as it explains why covariance can cause some issues. Contravariance is literally the opposite of covariance: parameters vary upward with subtyping. It is a lot less common partially because it is so counter-intuitive, though it does have one very important application: functions.
Notice the "-" variance annotation on the
Notice that none The reason for this rule is left as an exercise to the reader (hint: think about different cases as functions are subtyped, like my array example from above). With your new-found knowledge of co- and contravariance, you should be able to see why the following example will not compile:
The problem is that Our only two options here are to a) make
This is now valid. You can imagine that Notice that this trick only works if we return an instance of | |||||||||||||||||||||||||||||||||
|
See Scala by example, page 57+ for a full discussion of this. If I'm understanding your comment correctly, you need to reread the passage starting at the bottom of page 56 (basically, what I think you are asking for isn't type-safe without run time checks, which scala doesn't do, so you're out of luck). Translating their example to use your construct:
If you feel I'm not understanding your question (a distinct possibility), try adding more explanation / context to the problem description and I'll try again. In response to your edit: Immutable slots are a whole different situation...* smile * I hope the example above helped.
| |||||||||||||||||||||||||||
|
You need to apply a lower bound on the parameter. I'm having a hard time remembering the syntax, but I think it would look something like this:
The Scala-by-example is a bit hard to understand, a few concrete examples would have helped.
| |||||||||||||||
|