From ab97ce26bec8b3daab995aa329149562d82ee3f2 Mon Sep 17 00:00:00 2001 From: realwunan Date: Fri, 2 Nov 2018 11:54:43 +0800 Subject: [PATCH 1/2] Simplify Chinese translation of Scala Tour: self-types.md --- _zh-cn/tour/self-types.md | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/_zh-cn/tour/self-types.md b/_zh-cn/tour/self-types.md index 1cd47419c6..3352705de4 100644 --- a/_zh-cn/tour/self-types.md +++ b/_zh-cn/tour/self-types.md @@ -1,6 +1,6 @@ --- layout: tour -title: Self-types +title: 自类型 discourse: false @@ -13,3 +13,27 @@ language: zh-cn next-page: implicit-parameters previous-page: compound-types --- +自类型用于声明一个特质必须混入其他特质,尽管该特质没有直接扩展其他特质。 这使得所依赖的成员可以在没有导入的情况下使用。 + +自类型是一种缩小 `this` 类型或 `this` 别名类型的方法。 语法看起来像普通函数语法,但是意义完全不一样。 + +要在特质中使用自类型,写一个标识符,跟上要混入的另一个特质,以及 `=>`(例如 `someIdentifier: SomeOtherTrait =>`)。 +```tut +trait User { + def username: String +} + +trait Tweeter { + this: User => // 重新分配 this 的类型 + def tweet(tweetText: String) = println(s"$username: $tweetText") +} + +class VerifiedTweeter(val username_ : String) extends Tweeter with User { // 我们混入特质 User 因为 Tweeter 需要 + def username = s"real $username_" +} + +val realBeyoncé = new VerifiedTweeter("Beyoncé") +realBeyoncé.tweet("Just spilled my glass of lemonade") // 打印出 "real Beyoncé: Just spilled my glass of lemonade" +``` + +因为我们在特质 `trait Tweeter` 中定义了 `this: User =>`,现在变量 `username` 可以在 `tweet` 方法内使用。 这也意味着,由于 `VerifiedTweeter` 继承了 `Tweeter`,它还必须混入 `User`(使用 `with User`)。 From 1eff6ad92f008d42063785bfd1e3e8a4e015be22 Mon Sep 17 00:00:00 2001 From: realwunan Date: Mon, 3 Dec 2018 14:42:07 +0800 Subject: [PATCH 2/2] Fix Simplify Chinese Translation of Scala Tour: self types according to liufengyun's suggestion --- _zh-cn/tour/self-types.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/_zh-cn/tour/self-types.md b/_zh-cn/tour/self-types.md index 3352705de4..2942302cee 100644 --- a/_zh-cn/tour/self-types.md +++ b/_zh-cn/tour/self-types.md @@ -15,7 +15,7 @@ previous-page: compound-types --- 自类型用于声明一个特质必须混入其他特质,尽管该特质没有直接扩展其他特质。 这使得所依赖的成员可以在没有导入的情况下使用。 -自类型是一种缩小 `this` 类型或 `this` 别名类型的方法。 语法看起来像普通函数语法,但是意义完全不一样。 +自类型是一种细化 `this` 或 `this` 别名之类型的方法。 语法看起来像普通函数语法,但是意义完全不一样。 要在特质中使用自类型,写一个标识符,跟上要混入的另一个特质,以及 `=>`(例如 `someIdentifier: SomeOtherTrait =>`)。 ```tut @@ -24,7 +24,7 @@ trait User { } trait Tweeter { - this: User => // 重新分配 this 的类型 + this: User => // 重新赋予 this 的类型 def tweet(tweetText: String) = println(s"$username: $tweetText") }