Skip to content

Commit 7a48e66

Browse files
committed
Add Chinese translation of upper-type-bounds.
1 parent 51d91b6 commit 7a48e66

File tree

1 file changed

+40
-1
lines changed

1 file changed

+40
-1
lines changed

_zh-cn/tour/upper-type-bounds.md

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
layout: tour
3-
title: Upper Type Bounds
3+
title: 类型上界
44

55
discourse: false
66

@@ -13,3 +13,42 @@ language: zh-cn
1313
next-page: lower-type-bounds
1414
previous-page: variances
1515
---
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`的子类。

0 commit comments

Comments
 (0)