Skip to content

Commit 76e72cf

Browse files
committed
Provide better example of upper type bound usage. Previous one was not good, because its code was clearer without type bounds thanks to polymorphism.
1 parent 7469348 commit 76e72cf

File tree

1 file changed

+28
-16
lines changed

1 file changed

+28
-16
lines changed

tutorials/tour/upper-type-bounds.md

Lines changed: 28 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -11,27 +11,39 @@ tutorial-previous: variances
1111
---
1212

1313
In Scala, [type parameters](generic-classes.html) and [abstract types](abstract-types.html) may be constrained by a type bound. Such type bounds limit the concrete values of the type variables and possibly reveal more information about the members of such types. An _upper type bound_ `T <: A` declares that type variable `T` refers to a subtype of type `A`.
14-
Here is an example which relies on an upper type bound for the implementation of the polymorphic method `findSimilar`:
14+
Here is an example that demonstrates upper type bound for a type parameter of class `Cage`:
1515

1616
```tut
17-
trait Similar {
18-
def isSimilar(x: Any): Boolean
17+
abstract class Animal {
18+
def name: String
1919
}
20-
case class MyInt(x: Int) extends Similar {
21-
def isSimilar(m: Any): Boolean =
22-
m.isInstanceOf[MyInt] &&
23-
m.asInstanceOf[MyInt].x == x
20+
21+
abstract class Pet extends Animal {}
22+
23+
class Cat extends Pet {
24+
override def name: String = "Cat"
25+
}
26+
27+
class Dog extends Pet {
28+
override def name: String = "Dog"
29+
}
30+
31+
class Lion extends Animal {
32+
override def name: String = "Lion"
2433
}
25-
object UpperBoundTest extends App {
26-
def findSimilar[T <: Similar](e: T, xs: List[T]): Boolean =
27-
if (xs.isEmpty) false
28-
else if (e.isSimilar(xs.head)) true
29-
else findSimilar[T](e, xs.tail)
30-
val list: List[MyInt] = List(MyInt(1), MyInt(2), MyInt(3))
31-
println(findSimilar[MyInt](MyInt(4), list))
32-
println(findSimilar[MyInt](MyInt(2), list))
34+
35+
class Cage[P <: Pet](p: P) {
36+
def pet: P = p
37+
}
38+
39+
object Main extends App {
40+
var dogCage = new Cage[Dog](new Dog)
41+
var catCage = new Cage[Cat](new Cat)
42+
/* Cannot put Lion in a cage as Lion is not a Pet. */
43+
// var lionCage = new Cage[Lion](new Lion)
3344
}
3445
```
3546

36-
Without the upper type bound annotation it would not be possible to call method `isSimilar` in method `findSimilar`.
47+
An instance of class `Cage` may contain an animal with upper bound `Pet`. An animal of type `Lion` is not a pet and therefore cannot be put into a cage.
48+
3749
The usage of lower type bounds is discussed [here](lower-type-bounds.html).

0 commit comments

Comments
 (0)