Created
May 29, 2020 14:51
-
-
Save fancellu/7f27593c921075439405c4e2ce5baec5 to your computer and use it in GitHub Desktop.
Scala example of declaration side Type Covariance
This file contains hidden or 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
// take out the + and see the last few lines fail as doit then only takes Animal, and not its subtypes | |
// we output A, so + is fine, we are covariant | |
sealed trait ThisThatValue[+A] | |
object ThisThatValue { | |
final case class This[+A](value: A) extends ThisThatValue[A] | |
final case class That[+A](value: A) extends ThisThatValue[A] | |
} | |
sealed trait Animal { | |
val name: String | |
} | |
object Animal { | |
final case class Dog(name: String) extends Animal | |
final case class Cat(name: String) extends Animal | |
// if I added a new Animal class I would be warned | |
// in below match about being not exhaustive | |
//final case class Mouse(name:String) extends Animal | |
} | |
import ThisThatValue._ | |
import Animal._ | |
val dog1 = This(Dog("max")) | |
val cat1 = That(Cat("Kitty")) | |
val dog2 = That(Dog("Spot")) | |
def doit(cv: ThisThatValue[Animal]): Unit = | |
cv match { | |
case That(a: Dog) => println(s"that dog $a") | |
case That(a: Cat) => println(s"that cat $a") | |
case This(a) => println(s"this $a") | |
} | |
doit(dog1) | |
doit(cat1) | |
doit(dog2) |
This file contains hidden or 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
this Dog(max) | |
that cat Cat(Kitty) | |
that dog Dog(Spot) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment