Skip to content

Commit 8acb312

Browse files
authored
Merge pull request scala#1205 from realwunan/self-types
Simplify Chinese translation of Scala Tour: self-types.md
2 parents b15d245 + 1eff6ad commit 8acb312

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

_zh-cn/tour/self-types.md

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
layout: tour
3-
title: Self-types
3+
title: 自类型
44

55
discourse: false
66

@@ -13,3 +13,27 @@ language: zh-cn
1313
next-page: implicit-parameters
1414
previous-page: compound-types
1515
---
16+
自类型用于声明一个特质必须混入其他特质,尽管该特质没有直接扩展其他特质。 这使得所依赖的成员可以在没有导入的情况下使用。
17+
18+
自类型是一种细化 `this``this` 别名之类型的方法。 语法看起来像普通函数语法,但是意义完全不一样。
19+
20+
要在特质中使用自类型,写一个标识符,跟上要混入的另一个特质,以及 `=>`(例如 `someIdentifier: SomeOtherTrait =>`)。
21+
```tut
22+
trait User {
23+
def username: String
24+
}
25+
26+
trait Tweeter {
27+
this: User => // 重新赋予 this 的类型
28+
def tweet(tweetText: String) = println(s"$username: $tweetText")
29+
}
30+
31+
class VerifiedTweeter(val username_ : String) extends Tweeter with User { // 我们混入特质 User 因为 Tweeter 需要
32+
def username = s"real $username_"
33+
}
34+
35+
val realBeyoncé = new VerifiedTweeter("Beyoncé")
36+
realBeyoncé.tweet("Just spilled my glass of lemonade") // 打印出 "real Beyoncé: Just spilled my glass of lemonade"
37+
```
38+
39+
因为我们在特质 `trait Tweeter` 中定义了 `this: User =>`,现在变量 `username` 可以在 `tweet` 方法内使用。 这也意味着,由于 `VerifiedTweeter` 继承了 `Tweeter`,它还必须混入 `User`(使用 `with User`)。

0 commit comments

Comments
 (0)