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
Copy file name to clipboardExpand all lines: _tour/variances.md
+15-25Lines changed: 15 additions & 25 deletions
Original file line number
Diff line number
Diff line change
@@ -37,24 +37,19 @@ Both `Cat` and `Dog` are subtypes of `Animal`. The Scala standard library has a
37
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.
38
38
39
39
```tut
40
-
object CovarianceTest extends App {
41
-
def printAnimalNames(animals: List[Animal]): Unit = {
42
-
animals.foreach { animal =>
43
-
println(animal.name)
44
-
}
40
+
def printAnimalNames(animals: List[Animal]): Unit =
41
+
animals.foreach {
42
+
animal => println(animal.name)
45
43
}
46
44
47
-
val cats: List[Cat] = List(Cat("Whiskers"), Cat("Tom"))
48
-
val dogs: List[Dog] = List(Dog("Fido"), Dog("Rex"))
45
+
val cats: List[Cat] = List(Cat("Whiskers"), Cat("Tom"))
46
+
val dogs: List[Dog] = List(Dog("Fido"), Dog("Rex"))
49
47
50
-
printAnimalNames(cats)
51
-
// Whiskers
52
-
// Tom
48
+
// prints: Whiskers, Tom
49
+
printAnimalNames(cats)
53
50
54
-
printAnimalNames(dogs)
55
-
// Fido
56
-
// Rex
57
-
}
51
+
// prints: Fido, Rex
52
+
printAnimalNames(dogs)
58
53
```
59
54
60
55
### Contravariance
@@ -86,19 +81,14 @@ class CatPrinter extends Printer[Cat] {
86
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 substitute a `Printer[Animal]` for a `Printer[Cat]`, if we wish, and making `Printer[A]` contravariant allows us to do exactly that.
87
82
88
83
```tut
89
-
object ContravarianceTest extends App {
90
-
val myCat: Cat = Cat("Boots")
91
-
92
-
def printMyCat(printer: Printer[Cat]): Unit = {
93
-
printer.print(myCat)
94
-
}
84
+
def printMyCat(printer: Printer[Cat], cat: Cat): Unit =
85
+
printer.print(cat)
95
86
96
-
val catPrinter: Printer[Cat] = new CatPrinter
97
-
val animalPrinter: Printer[Animal] = new AnimalPrinter
87
+
val catPrinter: Printer[Cat] = new CatPrinter
88
+
val animalPrinter: Printer[Animal] = new AnimalPrinter
0 commit comments