Skip to content

Commit 079f0fd

Browse files
committed
language tour: remove unnecessary object wrappers
1 parent d473329 commit 079f0fd

File tree

1 file changed

+12
-15
lines changed

1 file changed

+12
-15
lines changed

_tour/variances.md

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -37,20 +37,19 @@ Both `Cat` and `Dog` are subtypes of `Animal`. The Scala standard library has a
3737
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.
3838

3939
```tut
40-
object CovarianceTest extends App {
41-
def printAnimalNames(animals: List[Animal]): Unit =
42-
animals.foreach {
43-
animal => println(animal.name)
44-
}
45-
}
40+
def printAnimalNames(animals: List[Animal]): Unit =
41+
animals.foreach {
42+
animal => println(animal.name)
43+
}
44+
4645
val cats: List[Cat] = List(Cat("Whiskers"), Cat("Tom"))
4746
val dogs: List[Dog] = List(Dog("Fido"), Dog("Rex"))
4847
4948
// prints: Whiskers, Tom
50-
CovarianceTest.printAnimalNames(cats)
49+
printAnimalNames(cats)
5150
5251
// prints: Fido, Rex
53-
CovarianceTest.printAnimalNames(dogs)
52+
printAnimalNames(dogs)
5453
```
5554

5655
### Contravariance
@@ -82,16 +81,14 @@ class CatPrinter extends Printer[Cat] {
8281
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.
8382

8483
```tut
85-
object ContravarianceTest extends App {
86-
def printMyCat(printer: Printer[Cat], cat: Cat): Unit = {
87-
printer.print(cat)
88-
}
89-
}
84+
def printMyCat(printer: Printer[Cat], cat: Cat): Unit =
85+
printer.print(cat)
86+
9087
val catPrinter: Printer[Cat] = new CatPrinter
9188
val animalPrinter: Printer[Animal] = new AnimalPrinter
9289
93-
ContravarianceTest.printMyCat(catPrinter, Cat("Boots"))
94-
ContravarianceTest.printMyCat(animalPrinter, Cat("Boots"))
90+
printMyCat(catPrinter, Cat("Boots"))
91+
printMyCat(animalPrinter, Cat("Boots"))
9592
```
9693

9794
The output of this program will be:

0 commit comments

Comments
 (0)