Skip to content

Commit 391c656

Browse files
authored
Merge pull request #1217 from realwunan/tuples
Simplify Chinese translation of Scala Tour: tuples.md
2 parents 6663178 + 91f6374 commit 391c656

File tree

1 file changed

+80
-3
lines changed

1 file changed

+80
-3
lines changed

_zh-cn/tour/tuples.md

Lines changed: 80 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
layout: tour
3-
title: Tuples
3+
title: 元组
44

55
discourse: true
66

@@ -15,5 +15,82 @@ previous-page: traits
1515
topics: tuples
1616
---
1717

18-
(this section of the tour has not been translated yet. pull request
19-
with translation welcome!)
18+
在 Scala 中,元组是一个可以容纳不同类型元素的类。
19+
元组是不可变的。
20+
21+
当我们需要从函数返回多个值时,元组会派上用场。
22+
23+
元组可以创建如下:
24+
25+
```tut
26+
val ingredient = ("Sugar" , 25):Tuple2[String, Int]
27+
```
28+
这将创建一个包含一个 String 元素和一个 Int 元素的元组。
29+
30+
Scala 中的元组包含一系列类:Tuple2,Tuple3等,直到 Tuple22。
31+
因此,当我们创建一个包含 n 个元素(n 位于 2 和 22 之间)的元组时,Scala 基本上就是从上述的一组类中实例化
32+
一个相对应的类,使用组成元素的类型进行参数化。
33+
上例中,`ingredient` 的类型为 `Tuple2[String, Int]`
34+
35+
## 访问元素
36+
37+
使用下划线语法来访问元组中的元素。
38+
'tuple._n' 取出了第 n 个元素(假设有足够多元素)。
39+
40+
```tut
41+
println(ingredient._1) // Sugar
42+
43+
println(ingredient._2) // 25
44+
```
45+
46+
## 解构元组数据
47+
48+
Scala 元组也支持解构。
49+
50+
```tut
51+
val (name, quantity) = ingredient
52+
53+
println(name) // Sugar
54+
55+
println(quantity) // 25
56+
```
57+
58+
元组解构也可用于模式匹配。
59+
60+
```tut
61+
val planetDistanceFromSun = List(("Mercury", 57.9), ("Venus", 108.2), ("Earth", 149.6 ), ("Mars", 227.9), ("Jupiter", 778.3))
62+
63+
planetDistanceFromSun.foreach{ tuple => {
64+
65+
tuple match {
66+
67+
case ("Mercury", distance) => println(s"Mercury is $distance millions km far from Sun")
68+
69+
case p if(p._1 == "Venus") => println(s"Venus is ${p._2} millions km far from Sun")
70+
71+
case p if(p._1 == "Earth") => println(s"Blue planet is ${p._2} millions km far from Sun")
72+
73+
case _ => println("Too far....")
74+
75+
}
76+
77+
}
78+
79+
}
80+
```
81+
82+
或者,在 'for' 表达式中。
83+
84+
```tut
85+
val numPairs = List((2, 5), (3, -7), (20, 56))
86+
87+
for ((a, b) <- numPairs) {
88+
89+
println(a * b)
90+
91+
}
92+
```
93+
94+
类型 `Unit` 的值 `()` 在概念上与类型 `Tuple0` 的值 `()` 相同。 `Tuple0` 只能有一个值,因为它没有元素。
95+
96+
用户有时可能在元组和 case 类之间难以选择。 通常,如果元素具有更多含义,则首选 case 类。

0 commit comments

Comments
 (0)