You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: _tour/self-types.md
+24-1
Original file line number
Diff line number
Diff line change
@@ -16,6 +16,9 @@ Self-types are a way to declare that a trait must be mixed into another trait, e
16
16
A self-type is a way to narrow the type of `this` or another identifier that aliases `this`. The syntax looks like normal function syntax but means something entirely different.
17
17
18
18
To use a self-type in a trait, write an identifier, the type of another trait to mix in, and a `=>` (e.g. `someIdentifier: SomeOtherTrait =>`).
19
+
20
+
{% tabs self-types_1 class=tabs-scala-version %}
21
+
{% tab 'Scala 2' for=self-types_1 %}
19
22
```scala mdoc
20
23
traitUser {
21
24
defusername:String
@@ -33,5 +36,25 @@ class VerifiedTweeter(val username_ : String) extends Tweeter with User { // We
33
36
valrealBeyoncé=newVerifiedTweeter("Beyoncé")
34
37
realBeyoncé.tweet("Just spilled my glass of lemonade") // prints "real Beyoncé: Just spilled my glass of lemonade"
35
38
```
36
-
37
39
Because we said `this: User =>` in `trait Tweeter`, now the variable `username` is in scope for the `tweet` method. This also means that since `VerifiedTweeter` extends `Tweeter`, it must also mix-in `User` (using `with User`).
classVerifiedTweeter(valusername_:String) extendsTweeter, User:// We mixin User because Tweeter required it
52
+
defusername=s"real $username_"
53
+
54
+
valrealBeyoncé=VerifiedTweeter("Beyoncé")
55
+
realBeyoncé.tweet("Just spilled my glass of lemonade") // prints "real Beyoncé: Just spilled my glass of lemonade"
56
+
```
57
+
Because we said `this: User =>` in `trait Tweeter`, now the variable `username` is in scope for the `tweet` method. This also means that since `VerifiedTweeter` extends `Tweeter`, it must also mix-in `User` (using `, User`).
0 commit comments