O'Reilly logo

Pragmatic Scala by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required