Covariance

object CovarianceTest extends App {
  def printAnimalNames(animals: List[Animal]): Unit = {
    animals.foreach { animal =>
      println(animal.name)
    }
  }

  val cats: List[Cat] = List(Cat("Whiskers"), Cat("Tom"))
  val dogs: List[Dog] = List(Dog("Fido"), Dog("Rex"))

  printAnimalNames(cats)
  // Whiskers
  // Tom

  printAnimalNames(dogs)
  // Fido
  // Rex
}

A type parameter A of a generic class can be made covariant by using the annotation +A. .

Covariance → is a → Variance.

Related concepts

Covariance

Covariance — Structure map

Clickable & Draggable!

Covariance — Related pages: