Skip to content

Commit e244cdd

Browse files
authored
Merge pull request #2488 from martijnhoekstra/varianceRewrite
2 parents d25d32e + 1ad1a91 commit e244cdd

File tree

1 file changed

+59
-75
lines changed

1 file changed

+59
-75
lines changed

_tour/variances.md

Lines changed: 59 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -10,19 +10,23 @@ previous-page: generic-classes
1010
redirect_from: "/tutorials/tour/variances.html"
1111
---
1212

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

1515
```scala mdoc
1616
class Foo[+A] // A covariant class
1717
class Bar[-A] // A contravariant class
1818
class Baz[A] // An invariant class
1919
```
2020

21-
### Covariance
21+
### Invariance
2222

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

25-
Consider this simple class structure:
25+
```scala mdoc
26+
class Box[A](var content: A)
27+
```
28+
29+
We're going to be putting values of type `Animal` in it. This type is defined as follows:
2630

2731
```scala mdoc
2832
abstract class Animal {
@@ -32,110 +36,90 @@ case class Cat(name: String) extends Animal
3236
case class Dog(name: String) extends Animal
3337
```
3438

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:
3840

3941
```scala mdoc
40-
def printAnimalNames(animals: List[Animal]): Unit =
41-
animals.foreach {
42-
animal => println(animal.name)
43-
}
42+
val myAnimal: Animal = Cat("Felix")
43+
```
4444

45-
val cats: List[Cat] = List(Cat("Whiskers"), Cat("Tom"))
46-
val dogs: List[Dog] = List(Dog("Fido"), Dog("Rex"))
45+
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:
4746

48-
// prints: Whiskers, Tom
49-
printAnimalNames(cats)
50-
51-
// prints: Fido, Rex
52-
printAnimalNames(dogs)
47+
```scala
48+
val myCatBox: Box[Cat] = new Box[Cat](Cat("Felix"))
49+
val myAnimalBox: Box[Animal] = myCatBox // this doesn't compile
50+
val myAnimal: Animal = myAnimalBox.content
5351
```
5452

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
5654

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+
```
5858

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

61-
```scala mdoc
62-
abstract class Printer[-A] {
63-
def print(value: A): Unit
64-
}
61+
```scala
62+
val myCat: Cat = myCatBox.content //myCat would be Fido the dog!
6563
```
6664

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

69-
```scala mdoc
70-
class AnimalPrinter extends Printer[Animal] {
71-
def print(animal: Animal): Unit =
72-
println("The animal's name is: " + animal.name)
73-
}
67+
### Covariance
7468

75-
class CatPrinter extends Printer[Cat] {
76-
def print(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.
8070

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

8373
```scala mdoc
84-
def printMyCat(printer: Printer[Cat], cat: Cat): Unit =
85-
printer.print(cat)
86-
87-
val catPrinter: Printer[Cat] = new CatPrinter
88-
val animalPrinter: Printer[Animal] = new AnimalPrinter
89-
90-
printMyCat(catPrinter, Cat("Boots"))
91-
printMyCat(animalPrinter, Cat("Boots"))
74+
class ImmutableBox[+A](val content: A)
75+
val catbox: ImmutableBox[Cat] = new ImmutableBox[Cat](Cat("Felix"))
76+
val animalBox: ImmutableBox[Animal] = catbox // now this compiles
9277
```
9378

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

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

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

10585
```scala mdoc
106-
class Container[A](value: A) {
107-
private var _value: A = value
108-
def getValue: A = _value
109-
def setValue(value: A): Unit = {
110-
_value = value
86+
def printAnimalNames(animals: List[Animal]): Unit =
87+
animals.foreach {
88+
animal => println(animal.name)
11189
}
112-
}
113-
```
11490

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
122-
```
91+
val cats: List[Cat] = List(Cat("Whiskers"), Cat("Tom"))
92+
val dogs: List[Dog] = List(Dog("Fido"), Dog("Rex"))
12393

124-
Fortunately, the compiler stops us long before we could get this far.
94+
// prints: Whiskers, Tom
95+
printAnimalNames(cats)
12596

126-
### Other Examples
97+
// prints: Fido, Rex
98+
printAnimalNames(dogs)
99+
```
127100

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
129102

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

132105
```scala mdoc
133-
abstract class SmallAnimal extends Animal
134-
case class Mouse(name: String) extends SmallAnimal
106+
abstract class Serializer[-A] {
107+
def serialize(a: A): String
108+
}
109+
110+
val animalSerializer: Serializer[Animal] = new Serializer[Animal] {
111+
def serialize(animal: Animal): String = s"""{ "name": "${animal.name}" }"""
112+
}
113+
val catSerializer: Serializer[Cat] = animalSerializer
114+
catSerializer.serialize(Cat("Felix"))
135115
```
136116

137-
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]`.
138120

139121
### Comparison With Other Languages
140122

141123
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

Comments
 (0)