Variance of Parameterized Type

Scala prevented us from assigning a reference of ArrayList[Int] to a reference of ArrayList[Any] in Type Inference for Generics and Collections. That’s a good thing; in general a collection of derived should not be assignable to a collection of base. However, there are times when we want some lenience to that rule. In those situations, we can ask Scala to permit otherwise invalid conversions. Tighten your seat belts—we’re in for a fun, but intense, ride.

Covariance and Contravariance

Scala will stop at compile time any conversions that may potentially lead to runtime failures. Specifically, as an example, it prevents the following code from compiling:

 
var​ arr1 = ​new​ ​Array​[​Int​](3)
 
var​ arr2: ​Array ...

Get Pragmatic Scala now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.