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: tutorials/tour/upper-type-bounds.md
+28-16Lines changed: 28 additions & 16 deletions
Original file line number
Diff line number
Diff line change
@@ -11,27 +11,39 @@ tutorial-previous: variances
11
11
---
12
12
13
13
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`:
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)
33
44
}
34
45
```
35
46
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
+
37
49
The usage of lower type bounds is discussed [here](lower-type-bounds.html).
0 commit comments