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 the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.