Variance Examples


today I would to introduce scala some. variance examples. Those magic +A -A what is it ?

I will show by the example, first declaring classes:

class Boss
class Worker extends Boss
class Student extends Worker

class TestClass[A]
class TestCovariantClass[+A]
class TestContravariantClass[-A]

Now decalring methods which takes as a param one of our Test classes:

// here will go Worker class only

def testMethod(x: TestClass[Worker]) {}

// Worker and Student

def testMethod2(x: TestCovariantClass[Worker]) {}

// Worker and Boss

def testMethod3(x: TestContravariantClass[Worker]) {}

As I commented to method "testMethod" can go only object of class Worker as it is [A] so no parent , no child , just this class.

testMethod2 takes covariant class [+A] so if we declare here Worker, we can put there object of class of course Worker and child of this class Student. Maybe to easy remember is connect "+" with that we are going forward so Worker -> Student.

testMethod3 is contravariant so we go backwards to Boss, so if we declared here Worker as this [A] here will go Worker and Boss:

testMethod(new TestClass[Worker])
testMethod(new TestCovariantClass[Worker])
testMethod(new TestCovariantClass[Student])
testMethod(new TestContravariantClass[Worker])
testMethod(new TestContravariantClass[Boss])