You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Variance is the correlation of subtyping relationships of complex types and the subtyping relationships of their component types. Scala supports variance annotations of type parameters of [generic classes](generic-classes.html), to allow them to be covariant, contravariant, or invariant if no annotations are used. The use of variance in the type system allows us to make intuitive connections between complex types, whereas the lack of variance can restrict the reuse of a class abstraction.
13
+
Variance lets you control how type parameters behave with regards to subtyping. Scala supports variance annotations of type parameters of [generic classes](generic-classes.html), to allow them to be covariant, contravariant, or invariant if no annotations are used. The use of variance in the type system allows us to make intuitive connections between complex types.
14
14
15
15
```scala mdoc
16
16
classFoo[+A] // A covariant class
17
17
classBar[-A] // A contravariant class
18
18
classBaz[A] // An invariant class
19
19
```
20
20
21
-
### Covariance
21
+
### Invariance
22
22
23
-
A type parameter `T` of a generic class can be made covariant by using the annotation `+T`. For some `class List[+T]`, making `T` covariant implies that for two types `A` and `B` where `B` is a subtype of `A`, then `List[B]` is a subtype of `List[A]`. This allows us to make very useful and intuitive subtyping relationships using generics.
23
+
By default, type parameters in Scala are invariant: subtyping relationships between the type parameters aren't reflected in the parameterized type. To explore why this works the way it does, we look at a simple parameterized type, the mutable box.
24
24
25
-
Consider this simple class structure:
25
+
```scala mdoc
26
+
classBox[A](varcontent:A)
27
+
```
28
+
29
+
We're going to be putting values of type `Animal` in it. This type is defined as follows:
26
30
27
31
```scala mdoc
28
32
abstractclassAnimal {
@@ -32,110 +36,90 @@ case class Cat(name: String) extends Animal
32
36
caseclassDog(name: String) extendsAnimal
33
37
```
34
38
35
-
Both `Cat` and `Dog` are subtypes of `Animal`. The Scala standard library has a generic immutable `sealed abstract class List[+A]` class, where the type parameter `A` is covariant. This means that a `List[Cat]` is a `List[Animal]`. A `List[Dog]` is also a `List[Animal]`. Intuitively, it makes sense that a list of cats and a list of dogs are each lists of animals, and you should be able to use either of them for in place of `List[Animal]`.
36
-
37
-
In the following example, the method `printAnimalNames` will accept a list of animals as an argument and print their names each on a new line. If `List[A]` were not covariant, the last two method calls would not compile, which would severely limit the usefulness of the `printAnimalNames` method.
39
+
We can say that `Cat` is a subtype of `Animal`, and that `Dog` is also a subtype of `Animal`. That means that the following is well-typed:
What about boxes? Is `Box[Cat]` a subtype of `Box[Animal]`, like `Cat` is a subtype of `Animal`? At first sight, it looks like that may be plausible, but if we try to do that, the compiler will tell us we have an error:
47
46
48
-
// prints: Whiskers, Tom
49
-
printAnimalNames(cats)
50
-
51
-
// prints: Fido, Rex
52
-
printAnimalNames(dogs)
47
+
```scala
48
+
valmyCatBox:Box[Cat] =newBox[Cat](Cat("Felix"))
49
+
valmyAnimalBox:Box[Animal] = myCatBox // this doesn't compile
50
+
valmyAnimal:Animal= myAnimalBox.content
53
51
```
54
52
55
-
### Contravariance
53
+
Why could this be a problem? We can get the cat from the box, and it's still an Animal, isn't it? Well, yes. But that's not all we can do. We can also replace the cat in the box with a different animal
56
54
57
-
A type parameter `A` of a generic class can be made contravariant by using the annotation `-A`. This creates a subtyping relationship between the class and its type parameter that is similar, but opposite to what we get with covariance. That is, for some `class Printer[-A]`, making `A` contravariant implies that for two types `A` and `B` where `A` is a subtype of `B`, `Printer[B]` is a subtype of `Printer[A]`.
55
+
```scala
56
+
mayAnimalBox.content =Dog("Fido")
57
+
```
58
58
59
-
Consider the `Cat`, `Dog`, and `Animal` classes defined above for the following example:
59
+
There now is a Dog in the Animal box. That's all fine, you can put Dogs in Animal boxes, because Dogs are Animals. But our Animal Box is a Cat Box! You can't put a Dog in a Cat box. If we could, and then try to get the cat from our Cat Box, it would turn out to be a dog, breaking type soundness.
60
60
61
-
```scala mdoc
62
-
abstractclassPrinter[-A] {
63
-
defprint(value: A):Unit
64
-
}
61
+
```scala
62
+
valmyCat:Cat= myCatBox.content //myCat would be Fido the dog!
65
63
```
66
64
67
-
A `Printer[A]` is a simple class that knows how to print out some type `A`. Let's define some subclasses for specific types:
65
+
From this, we have to conclude that `Box[Cat]` and `Box[Animal]` can't have a subtyping relationship, even though `Cat` and `Animal` do.
68
66
69
-
```scala mdoc
70
-
classAnimalPrinterextendsPrinter[Animal] {
71
-
defprint(animal: Animal):Unit=
72
-
println("The animal's name is: "+ animal.name)
73
-
}
67
+
### Covariance
74
68
75
-
classCatPrinterextendsPrinter[Cat] {
76
-
defprint(cat: Cat):Unit=
77
-
println("The cat's name is: "+ cat.name)
78
-
}
79
-
```
69
+
The problem we ran in to above, is that because we could put a Dog in an Animal Box, a Cat Box can't be an Animal Box.
80
70
81
-
If a `Printer[Cat]` knows how to print any `Cat` to the console, and a `Printer[Animal]` knows how to print any `Animal` to the console, it makes sense that a `Printer[Animal]` would also know how to print any `Cat`. The inverse relationship does not apply, because a `Printer[Cat]` does not know how to print any `Animal` to the console. Therefore, we should be able to use a `Printer[Animal]` in place of `Printer[Cat]`, if we wish, and making `Printer[A]` contravariant allows us to do exactly that.
71
+
But what if we couldn't put a Dog in the box? Then we could just get our Cat back out and that's not a problem, so than it could follow the subtyping relationship. It turns out, that's indeed something we can do.
valanimalBox:ImmutableBox[Animal] = catbox // now this compiles
92
77
```
93
78
94
-
The output of this program will be:
79
+
We say that `ImmutableBox` is *covariant* in `A`, and this is indicated by the `+` before the `A`.
95
80
96
-
```
97
-
The cat's name is: Boots
98
-
The animal's name is: Boots
99
-
```
81
+
More formally, that gives us the following relationship: given some `class Cov[+T]`, then if `A` is a subtype of `B`, `Cov[A]` is a subtype of `Cov[B]`. This allows us to make very useful and intuitive subtyping relationships using generics.
100
82
101
-
### Invariance
102
-
103
-
Generic classes in Scala are invariant by default. This means that they are neither covariant nor contravariant. In the context of the following example, `Container` class is invariant. A `Container[Cat]` is _not_ a `Container[Animal]`, nor is the reverse true.
83
+
In the following less contrived example, the method `printAnimalNames` will accept a list of animals as an argument and print their names each on a new line. If `List[A]` were not covariant, the last two method calls would not compile, which would severely limit the usefulness of the `printAnimalNames` method.
104
84
105
85
```scala mdoc
106
-
classContainer[A](value: A) {
107
-
privatevar_value:A= value
108
-
defgetValue:A= _value
109
-
defsetValue(value: A):Unit= {
110
-
_value = value
86
+
defprintAnimalNames(animals: List[Animal]):Unit=
87
+
animals.foreach {
88
+
animal => println(animal.name)
111
89
}
112
-
}
113
-
```
114
90
115
-
It may seem like a `Container[Cat]` should naturally also be a `Container[Animal]`, but allowing a mutable generic class to be covariant would not be safe. In this example, it is very important that `Container` is invariant. Supposing `Container` was actually covariant, something like this could happen:
116
-
117
-
```
118
-
val catContainer: Container[Cat] = new Container(Cat("Felix"))
119
-
val animalContainer: Container[Animal] = catContainer
120
-
animalContainer.setValue(Dog("Spot"))
121
-
val cat: Cat = catContainer.getValue // Oops, we'd end up with a Dog assigned to a Cat
Fortunately, the compiler stops us long before we could get this far.
94
+
// prints: Whiskers, Tom
95
+
printAnimalNames(cats)
125
96
126
-
### Other Examples
97
+
// prints: Fido, Rex
98
+
printAnimalNames(dogs)
99
+
```
127
100
128
-
Another example that can help one understand variance is `trait Function1[-T, +R]` from the Scala standard library. `Function1` represents a function with one parameter, where the first type parameter `T` represents the parameter type, and the second type parameter `R` represents the return type. A `Function1` is contravariant over its parameter type, and covariant over its return type. For this example we'll use the literal notation `A => B` to represent a `Function1[A, B]`.
101
+
### Contravariance
129
102
130
-
Assume the similar `Cat`, `Dog`, `Animal` inheritance tree used earlier, plus the following:
103
+
We've seen we can accomplish covariance by making sure that we can't put something in the covariant type, but only get something out. What if we had the opposite, something you can put something in, but can't take out? This situation arises if we have something like a serializer, that takes values of type A, and converts them to a serialized format.
Suppose we're working with functions that accept types of animals, and return the types of food they eat. If we would like a `Cat => SmallAnimal` (because cats eat small animals), but are given a `Animal => Mouse` instead, our program will still work. Intuitively an `Animal => Mouse` will still accept a `Cat` as an argument, because a `Cat` is an `Animal`, and it returns a `Mouse`, which is also a `SmallAnimal`. Since we can safely and invisibly substitute the former with the latter, we can say `Animal => Mouse` is a subtype of `Cat => SmallAnimal`.
117
+
We say that `Serializer` is *contravariant* in `A`, and this is indicated by the `-` before the `A`. A more general serializer is a subtype of a more specific serializer.
118
+
119
+
More formally, that gives us the reverse relationship: given some `class Contra[-T]`, then if `A` is a subtype of `B`, `Cov[B]` is a subtype of `Cov[A]`.
138
120
139
121
### Comparison With Other Languages
140
122
141
123
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).
124
+
125
+
Scala's tendency towards immutable types makes it that covariant and contravariant types are more common than in other languages, since a mutable generic type must be invariant.
0 commit comments