Skip to content

Commit 20cf3a2

Browse files
committed
Fix problems in variance section and make code compile
1 parent c62f5d4 commit 20cf3a2

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

_overviews/scala3-book/types-variance.md

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,21 +13,21 @@ To explain variance, let us assume the following type definitions:
1313
```scala
1414
trait Item { def productNumber: String }
1515
trait Buyable extends Item { def price: Int }
16-
trait Book extends CartItem { def isbn: String }
16+
trait Book extends Buyable { def isbn: String }
1717
```
1818

1919
Let us also assume the following parameterized types:
2020
```scala
2121
// an example of an invariant type
22-
class Pipeline[T]:
22+
trait Pipeline[T]:
2323
def process(t: T): T
2424

2525
// an example of an covariant type
26-
class Producer[+T]:
26+
trait Producer[+T]:
2727
def make: T
2828

2929
// an example of an contravariant type
30-
class Consumer[-T]:
30+
trait Consumer[-T]:
3131
def take(t: T): Unit
3232
```
3333
In general there are three modes of variance:
@@ -50,7 +50,9 @@ def oneOf(
5050
p2: Pipeline[Buyable],
5151
b: Buyable
5252
): Buyable =
53-
if p1.price < p2.price then p1.process(b) else p2.process(b)
53+
val b1 = p1.process(b)
54+
val b2 = p2.process(b)
55+
if b1.price < b2.price then b1 else b2
5456
```
5557
Now, recall that we have the following _subtyping relationship_ between our types:
5658
```scala
@@ -76,7 +78,7 @@ As a caller of `make`, we will be happy to also accept a `Book`, which is a subt
7678

7779
This is illustrated by the following example, where the function `makeTwo` expects a `Producer[Buyable]`:
7880
```scala
79-
def makeTwo(p: Producer[Buyable]): Double =
81+
def makeTwo(p: Producer[Buyable]): Int =
8082
p.make.price + p.make.price
8183
```
8284
It is perfectly fine to pass a producer for books:

0 commit comments

Comments
 (0)