Skip to content

Commit 46beedb

Browse files
benluojulienrf
authored andcommitted
add code tab in _zh-cn/overviews/scala3-book/fp-immutable-values.md
1 parent 8858474 commit 46beedb

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

_zh-cn/overviews/scala3-book/fp-immutable-values.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,44 +28,64 @@ permalink: "/zh-cn/scala3/book/:title.html"
2828
例如,假设你有一个名字列表——一个 `List[String]`——都是小写的,你想找到所有以字母 `"j"` 开头的名字,并且把找出来的名字大写。
2929
在 FP 中,您编写以下代码:
3030

31+
{% tabs fp-list %}
32+
{% tab 'Scala 2 and 3' %}
3133
```scala
3234
val a = List("jane", "jon", "mary", "joe")
3335
val b = a.filter(_.startsWith("j"))
3436
.map(_.capitalize)
3537
```
38+
{% endtab %}
39+
{% endtabs %}
3640

3741
如图所示,您不会改变原始列表 `a`
3842
相反,您将过滤和转换函数应用于 `a` 以创建一个新集合,并将该结果分配给新的不可变变量 `b`
3943

4044
同样,在 FP 中,您不会创建具有可变 `var` 构造函数参数的类。
4145
也就是说,你不要这样写:
4246

47+
{% tabs fp--class-variables %}
48+
{% tab 'Scala 2 and 3' %}
4349
```scala
4450
// don’t do this in FP
4551
class Person(var firstName: String, var lastName: String)
4652
--- ---
4753
```
54+
{% endtab %}
55+
{% endtabs %}
4856

4957
相反,您通常创建 `case` 类,其构造函数参数默认为 `val`
5058

59+
{% tabs fp-immutable-case-class %}
60+
{% tab 'Scala 2 and 3' %}
5161
```scala
5262
case class Person(firstName: String, lastName: String)
5363
```
64+
{% endtab %}
65+
{% endtabs %}
5466

5567
现在你创建一个 `Person` 实例作为 `val` 字段:
5668

69+
{% tabs fp-case-class-creation %}
70+
{% tab 'Scala 2 and 3' %}
5771
```scala
5872
val reginald = Person("Reginald", "Dwight")
5973
```
74+
{% endtab %}
75+
{% endtabs %}
6076

6177
然后,当您需要对数据进行更改时,您可以使用 `case` 类附带的 `copy` 方法来“在制作副本时更新数据”,如下所示:
6278

79+
{% tabs fp-case-class-copy %}
80+
{% tab 'Scala 2 and 3' %}
6381
```scala
6482
val elton = reginald.copy(
6583
firstName = "Elton", // update the first name
6684
lastName = "John" // update the last name
6785
)
6886
```
87+
{% endtab %}
88+
{% endtabs %}
6989

7090
还有其他处理不可变集合和变量的技术,但希望这些示例能让您尝试一下这些技术。
7191

0 commit comments

Comments
 (0)