Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Covariance and Contravariance in Scala
// (c) 2015 Joern Dinkla, see http://www.dinkla.net/en/programming/scala-covariance-contravariance.html
abstract class Animal
class Cat extends Animal {
def meow() : Unit = println("meow")
}
class Dog extends Animal
def mkPair(a: Animal, b: Animal) = (a,b)
val ps = mkPair(new Cat, new Dog)
val cs = List(new Cat, new Cat)
val ds = List(new Dog, new Dog)
val as = List(new Cat, new Dog)
class Getter[T](val value: T) {
def get = value
}
val gc = new Getter[Cat](new Cat)
val ga = new Getter[Animal](new Cat)
gc.get
gc.get : Animal
ga.get
ga.get : Cat
class Setter[T] {
def set(v: T): Unit = { }
}
val sc = new Setter[Cat]
val sa = new Setter[Animal]
sa.set(new Cat : Animal)
sa.set(new Cat)
sc.set(new Cat)
sc.set(new Cat : Animal)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment