File tree Expand file tree Collapse file tree 1 file changed +40
-1
lines changed Expand file tree Collapse file tree 1 file changed +40
-1
lines changed Original file line number Diff line number Diff line change 1
1
---
2
2
layout : tour
3
- title : Upper Type Bounds
3
+ title : 类型上界
4
4
5
5
discourse : false
6
6
@@ -13,3 +13,42 @@ language: zh-cn
13
13
next-page : lower-type-bounds
14
14
previous-page : variances
15
15
---
16
+
17
+ 在Scala中,[ 类型参数] ( generic-classes.html ) 和[ 抽象类型] ( abstract-types.html ) 都可以有一个类型边界约束。这种类型边界在限制类型变量实际取值的同时还能展露类型成员的更多信息。比如像` T <: A ` 这样声明的类型上界表示类型变量` T ` 应该是类型` A ` 的子类。下面的例子展示了类` PetContainer ` 的一个类型参数的类型上界。
18
+
19
+ ``` tut
20
+ abstract class Animal {
21
+ def name: String
22
+ }
23
+
24
+ abstract class Pet extends Animal {}
25
+
26
+ class Cat extends Pet {
27
+ override def name: String = "Cat"
28
+ }
29
+
30
+ class Dog extends Pet {
31
+ override def name: String = "Dog"
32
+ }
33
+
34
+ class Lion extends Animal {
35
+ override def name: String = "Lion"
36
+ }
37
+
38
+ class PetContainer[P <: Pet](p: P) {
39
+ def pet: P = p
40
+ }
41
+
42
+ val dogContainer = new PetContainer[Dog](new Dog)
43
+ val catContainer = new PetContainer[Cat](new Cat)
44
+ ```
45
+
46
+ ``` tut:fail
47
+ // this would not compile
48
+ val lionContainer = new PetContainer[Lion](new Lion)
49
+ ```
50
+ 类` PetContainer ` 接受一个必须是` Pet ` 子类的类型参数` P ` 。因为` Dog ` 和` Cat ` 都是` Pet ` 的子类,所以可以构造` PetContainer[Dog] ` 和` PetContainer[Cat] ` 。但在尝试构造` PetContainer[Lion] ` 的时候会得到下面的错误信息:
51
+
52
+ ` type arguments [Lion] do not conform to class PetContainer's type parameter bounds [P <: Pet] `
53
+
54
+ 这是因为` Lion ` 并不是` Pet ` 的子类。
You can’t perform that action at this time.
0 commit comments