I was reading through http://oldfashionedsoftware.com/2008/08/26/variance-basics-in-java-and-scala/
and am looking at the code
class CoVar[+T](param1: T) {
def method1(param2: T) = { }
def method2: T = { param1 }
def method3: List[T] = { List[T](param1) }
def method4[U >: T]: List[U] = { List[U](param1) }
val val1: T = method2
val val2: Any = param1
var var1: T = method2
var var2: Any = param1
}
then if I were to have a
val covar1 = new CoVar(new Car)
val covar2: CoVar[Vehicle] = covar1 //completely legal with covariant
Now, let's walk through the methods
- method1 - I don't get why this doesn't compile and that is my main question
- method2 - param1 is a car and method2 returns a Vehicle which is fine since Car is a Vehicle
- method3 - since List[Vehicle] is returned and Car is a Vehicle this is fine
- var1 - same question I believe and not too different
I would think this would be ok with method1(param: Vehicle) since I can pass in a new Vehicle just fine or a new Car just fine
but the original CoVar class does not compile since it says method1 is contravariant position. I thought contravariant would mean I could pass in a
Now, walking through this with ContraVar, and method1 again we have
class ContraVar[-T](param1: T) {
def method1(param2: T) = { }
val val2: Any = param1
var var2: Any = param1
}
val temp1 = new ContraVar(new Car)
val temp2: ContraVar[Ford] = temp1
temp2.method1(new Ford)
temp2.method1(new FordMustang)
temp2.method1(new Car) //fails to compile(good)
which work just fine. Can someone please explain why method1 breaks on CoVar? Perhaps I am headed down the completely wrong path on what would go wrong with letting method1 compile just fine?
thanks, Dean