Following on from this question, can someone explain the following in Scala:
class Slot[+T] (var some: T) {
// DOES NOT COMPILE
// \"COVARIANT paramete
@Daniel has explained it very well. But to explain it in short, if it was allowed:
class Slot[+T](var some: T) {
def get: T = some
}
val slot: Slot[Dog] = new Slot[Dog](new Dog)
val slot2: Slot[Animal] = slot //because of co-variance
slot2.some = new Animal //legal as some is a var
slot.get ??
slot.get
will then throw an error at runtime as it was unsuccessful in converting an Animal
to Dog
(duh!).
In general mutability doesn't go well with co-variance and contra-variance. That is the reason why all Java collections are invariant.