Skip to content

Commit db4042a

Browse files
authored
Merge pull request #1207 from realwunan/type-inference
Simplify Chinese translation of Scala Tour: type-inference.md
2 parents f60110f + fdad7cd commit db4042a

File tree

1 file changed

+63
-1
lines changed

1 file changed

+63
-1
lines changed

_zh-cn/tour/type-inference.md

Lines changed: 63 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
layout: tour
3-
title: Type Inference
3+
title: 类型推断
44

55
discourse: false
66

@@ -13,3 +13,65 @@ language: zh-cn
1313
next-page: operators
1414
previous-page: polymorphic-methods
1515
---
16+
17+
Scala 编译器通常可以推断出表达式的类型,因此你不必显式地声明它。
18+
19+
## 省略类型
20+
21+
```tut
22+
val businessName = "Montreux Jazz Café"
23+
```
24+
编译器可以发现 `businessName` 是 String 类型。 它的工作原理和方法类似:
25+
26+
```tut
27+
def squareOf(x: Int) = x * x
28+
```
29+
编译器可以推断出方法的返回类型为 `Int`,因此不需要明确地声明返回类型。
30+
31+
对于递归方法,编译器无法推断出结果类型。 下面这个程序就是由于这个原因而编译失败:
32+
33+
```tut:fail
34+
def fac(n: Int) = if (n == 0) 1 else n * fac(n - 1)
35+
```
36+
37+
当调用 [多态方法](polymorphic-methods.html) 或实例化 [泛型类](generic-classes.html) 时,也不必明确指定类型参数。 Scala 编译器将从上下文和实际方法的类型/构造函数参数的类型推断出缺失的类型参数。
38+
39+
看下面两个例子:
40+
41+
```tut
42+
case class MyPair[A, B](x: A, y: B);
43+
val p = MyPair(1, "scala") // type: MyPair[Int, String]
44+
45+
def id[T](x: T) = x
46+
val q = id(1) // type: Int
47+
```
48+
49+
编译器使用传给 `MyPair` 参数的类型来推断出 `A``B` 的类型。对于 `x` 的类型同样如此。
50+
51+
## 参数
52+
53+
编译器从不推断方法形式参数的类型。 但是,在某些情况下,当函数作为参数传递时,编译器可以推断出匿名函数形式参数的类型。
54+
55+
```tut
56+
Seq(1, 3, 4).map(x => x * 2) // List(2, 6, 8)
57+
```
58+
59+
方法 map 的形式参数是 `f: A => B`。 因为我们把整数放在 `Seq` 中,编译器知道 `A``Int` 类型 (即 `x` 是一个整数)。 因此,编译器可以从 `x * 2` 推断出 `B``Int` 类型。
60+
61+
## 何时 _不要_ 依赖类型推断
62+
63+
通常认为,公开可访问的 API 成员应该具有显示类型声明以增加可读性。 因此,我们建议你将代码中向用户公开的任何 API 明确指定类型。
64+
65+
此外,类型推断有时会推断出太具体的类型。 假设我们这么写:
66+
67+
```tut
68+
var obj = null
69+
```
70+
71+
我们就不能进行重新赋值:
72+
73+
```tut:fail
74+
obj = new AnyRef
75+
```
76+
77+
它不能编译,因为 `obj` 推断出的类型是 `Null`。 由于该类型的唯一值是 `null`,因此无法分配其他的值。

0 commit comments

Comments
 (0)