← Back to Scala Course | Chapter 12: Advanced Features | Lesson 4 of 7

Variance (Covariant/Contravariant)

Variance (Covariant/Contravariant)

Covariance, declared with class Box[+T], lets Box[Dog] be used where Box[Animal] is expected, preserving the subtype relationship of the type parameter. Contravariance, declared with class Printer[-T], works the opposite direction -- a Printer[Animal] can be used where a Printer[Dog] is expected, since it can handle anything an Animal-or-more-general printer could. By default (no +/-), a type parameter is invariant, meaning no such substitution is allowed at all.

Note: Covariant (+T) type parameters are generally restricted to output/return positions only -- using one as a method parameter type usually causes a compile error.

Example: Variance (Covariant/Contravariant)

markup
class Animal(val name: String)
class Dog(name: String) extends Animal(name)

class Box[+T](val item: T)

object Main extends App {
  val dogBox: Box[Dog] = new Box(new Dog("Rex"))
  val animalBox: Box[Animal] = dogBox // allowed because Box is covariant

  println(animalBox.item.name)
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.