Last active
August 29, 2015 14:24
-
-
Save jdinkla/5562e909a1064333aed6 to your computer and use it in GitHub Desktop.
Covariance and Contravariance in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// (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