Skip to content

Instantly share code, notes, and snippets.

@fancellu
Created May 29, 2020 14:51
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fancellu/7f27593c921075439405c4e2ce5baec5 to your computer and use it in GitHub Desktop.
Save fancellu/7f27593c921075439405c4e2ce5baec5 to your computer and use it in GitHub Desktop.
Scala example of declaration side Type Covariance
// 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 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