Friday, 29 December 2017

Varience in scala

Seriously I never remember which is which.

Covariance


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


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


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

Scala with Cats: Answers to revision questions

I'm studying the 'Scala with Cats' book. I want the information to stick so I am applying a technique from 'Ultralearning...