Skip to content

Commit 63cb58f

Browse files
authored
Merge pull request scala#1206 from realwunan/polymorphic-methods
Simplify Chinese translation fo Scala Tour: polymorphic-methods.md
2 parents 8acb312 + b0c9d73 commit 63cb58f

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

_zh-cn/tour/polymorphic-methods.md

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
layout: tour
3-
title: Polymorphic Methods
3+
title: 多态方法
44

55
discourse: false
66

@@ -13,3 +13,24 @@ language: zh-cn
1313
next-page: type-inference
1414
previous-page: implicit-conversions
1515
---
16+
17+
Scala 中的方法可以按类型和值进行参数化。 语法和泛型类类似。 类型参数括在方括号中,而值参数括在圆括号中。
18+
19+
看下面的例子:
20+
21+
```tut
22+
def listOfDuplicates[A](x: A, length: Int): List[A] = {
23+
if (length < 1)
24+
Nil
25+
else
26+
x :: listOfDuplicates(x, length - 1)
27+
}
28+
println(listOfDuplicates[Int](3, 4)) // List(3, 3, 3, 3)
29+
println(listOfDuplicates("La", 8)) // List(La, La, La, La, La, La, La, La)
30+
```
31+
32+
方法 `listOfDuplicates` 具有类型参数 `A` 和值参数 `x``length`。 值 `x``A` 类型。 如果 `length < 1`,我们返回一个空列表。 否则我们将 `x` 添加到递归调用返回的重复列表中。 (注意,`::` 表示将左侧的元素添加到右侧的列表中。)
33+
34+
上例中第一次调用方法时,我们显式地提供了类型参数 `[Int]`。 因此第一个参数必须是 `Int` 类型,并且返回类型为 `List[Int]`
35+
36+
上例中第二次调用方法,表明并不总是需要显式提供类型参数。 编译器通常可以根据上下文或值参数的类型来推断。 在这个例子中,`"La"` 是一个 `String`,因此编译器知道 `A` 必须是 `String`

0 commit comments

Comments
 (0)