Seriously I never remember which is which.
Covariance
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
sealed trait InMyPocket[+A] | |
sealed trait Cuddler | |
final case class Puppy(name: String) extends Cuddler | |
object VarianceExample { | |
var dog: InMyPocket[Puppy] = new InMyPocket[Puppy] {} | |
var cuddler: InMyPocket[Cuddler] = new InMyPocket[Cuddler] {} | |
cuddler = dog | |
// dog = cuddler // doesnt compile | |
} |
Contravarience
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
sealed trait InMyPocket[-A] | |
sealed trait Cuddler | |
final case class Puppy(name: String) extends Cuddler | |
object VarianceExample { | |
var dog: InMyPocket[Puppy] = new InMyPocket[Puppy] {} | |
var cuddler: InMyPocket[Cuddler] = new InMyPocket[Cuddler] {} | |
// cuddler = dog // doesnt compile | |
dog = cuddler | |
} |
Invariance
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
sealed trait InMyPocket[A] | |
sealed trait Cuddler | |
final case class Puppy(name: String) extends Cuddler | |
object VarianceExample { | |
var dog: InMyPocket[Puppy] = new InMyPocket[Puppy] {} | |
var cuddler: InMyPocket[Cuddler] = new InMyPocket[Cuddler] {} | |
// cuddler = dog // doesnt compile | |
// dog = cuddler // doesnt compile | |
} |
No comments:
Post a Comment