Skip to content

Commit a5a5cc6

Browse files
flomebulbishabosha
andauthored
Add code tabs for _tour/self-types (#2553)
* Add code tabs for _tour/self-types * Update _tour/self-types.md Yes. Co-authored-by: Jamie Thompson <[email protected]> Co-authored-by: Jamie Thompson <[email protected]>
1 parent cb7225c commit a5a5cc6

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

_tour/self-types.md

+24-1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@ Self-types are a way to declare that a trait must be mixed into another trait, e
1616
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.
1717

1818
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 %}
1922
```scala mdoc
2023
trait User {
2124
def username: String
@@ -33,5 +36,25 @@ class VerifiedTweeter(val username_ : String) extends Tweeter with User { // We
3336
val realBeyoncé = new VerifiedTweeter("Beyoncé")
3437
realBeyoncé.tweet("Just spilled my glass of lemonade") // prints "real Beyoncé: Just spilled my glass of lemonade"
3538
```
36-
3739
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`).
40+
41+
{% endtab %}
42+
{% tab 'Scala 3' for=self-types_1 %}
43+
```scala
44+
trait User:
45+
def username: String
46+
47+
trait Tweeter:
48+
this: User => // reassign this
49+
def tweet(tweetText: String) = println(s"$username: $tweetText")
50+
51+
class VerifiedTweeter(val username_ : String) extends Tweeter, User: // We mixin User because Tweeter required it
52+
def username = s"real $username_"
53+
54+
val realBeyoncé = 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`).
58+
59+
{% endtab %}
60+
{% endtabs %}

0 commit comments

Comments
 (0)