Skip to content

Instantly share code, notes, and snippets.

@jdinkla
Last active August 29, 2015 14:24
Show Gist options
  • Save jdinkla/5562e909a1064333aed6 to your computer and use it in GitHub Desktop.
Save jdinkla/5562e909a1064333aed6 to your computer and use it in GitHub Desktop.
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