As per the definition of contravariance (super class instances will be accepted), my last statement in the below code snippet, should be accepted; but it is thrown with type error. Can you please correct my understanding.
class A
class B extends A
class C extends B
abstract class Box[-T] {
def set(x : T) :Unit
}
val x = new Box[B] {
def set(b:B) = Console println "B"
}
val y = new Box[A] {
def set(a:A) = Console println "A"
}
val z = new Box[C] {
def set(c:C) = Console println "C"
}
x.set(new A) <-- Type error
But x.set(new C) is fine! So even though "contravariant parameters are accepted as method parameters" is in fact, are covariant parameters actually.
You are confusing how contravariance works.
xis a Box[B] as such,setaccepts values of typeB(or any subtype ofBbecause that is what Liskvo says).However, Box[A] is a subtype of a Box[B]. So you could have passed
ywherexis expected. Because a Box that can store anyAcan store aB.But, a Box that can store only
Bs can not store and arbitraryA.