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

Variance (Covariant/Contravariant)

Variance describes whether a box of one type can stand in for a box of a related type, like a basket of cats counting as a basket of animals. Scala uses plus and minus signs to say how.
Syntax
scala
class Box[+T](value: T)    // covariant
trait Handler[-T]          // 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)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Declaring a mutable field of a covariant type, like class Box[+T](var item: T), which does not compile.
  2. Assuming Box[Dog] is a Box[Animal] without +T, since Scala classes are invariant by default.
  3. Mixing up +T and -T, when covariance is for producers and contravariance for consumers.
🔒

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.