Generics and Variance

Generics in Scala allow classes and methods to operate on types specified as parameters.

Generic Class Example

class Box[T](val value: T) {
  def get: T = value
}

Variance controls subtype relationships of parameterized types:

  • +T: Covariant
  • -T: Contravariant
  • T: Invariant
class Covariant[+T]
class Contravariant[-T]
class Invariant[T]
← PrevNext →