Skip to content

Commit de0da1d

Browse files
KarahanSbishabosha
authored andcommitted
add a subsection explaining the relationship between immutability and variance
1 parent d2c43ef commit de0da1d

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

_tour/variances.md

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,19 @@ We say that `Serializer` is *contravariant* in `A`, and this is indicated by the
193193

194194
More formally, that gives us the reverse relationship: given some `class Contra[-T]`, then if `A` is a subtype of `B`, `Contra[B]` is a subtype of `Contra[A]`.
195195

196+
### Immutability and Variance
197+
Immutability constitutes an important part of the design decision behind the variance. As previously explained, Scala collections systematically distinguish between [Mutable and Immutable Collections](https://docs.scala-lang.org/overviews/collections-2.13/overview.html). For collections, mutability combined with covariance may break type safety. ```List``` is a covariant collection, while ```Array``` is an invariant collection. ```List``` is a collection in package ```scala.collection.immutable```, therefore it is guaranteed to be immutable for everyone. Whereas, ```Array``` is mutable, that is, you can change, add, or remove elements of an ```Array```. Following initialization wouldn't get compiled since ```Array[Int]``` is not a subtype of ```Array[Any]``` although ```Int``` is a subtype of ```Any```.
198+
```scala mdoc
199+
val arr:Array[Any] = Array[Int](1,2,3)
200+
```
201+
The reason is that if Scala allowed mutable collections to be covariant, then the type error in the following statements wouldn't be catched by the compiler and it would break type safety.
202+
```scala mdoc
203+
val arr:Array[Int] = Array[Int](1,2,3)
204+
val arr2:Array[Any] = arr
205+
arr2(0) = 3.14
206+
```
207+
208+
196209
### Comparison With Other Languages
197210

198211
Variance is supported in different ways by some languages that are similar to Scala. For example, variance annotations in Scala closely resemble those in C#, where the annotations are added when a class abstraction is defined (declaration-site variance). In Java, however, variance annotations are given by clients when a class abstraction is used (use-site variance).

0 commit comments

Comments
 (0)