Skip to content

Commit ec6a1f2

Browse files
committed
Rewrote self-type tour
1 parent b5c7331 commit ec6a1f2

File tree

2 files changed

+37
-123
lines changed

2 files changed

+37
-123
lines changed

tutorials/tour/_posts/2017-02-13-explicitly-typed-self-references.md

Lines changed: 0 additions & 123 deletions
This file was deleted.
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
---
2+
layout: tutorial
3+
title: Self-type
4+
5+
disqus: true
6+
7+
tutorial: scala-tour
8+
categories: tour
9+
num: 25
10+
next-page: implicit-parameters
11+
previous-page: compound-types
12+
prerequisite-knowledge: nested-classes, mixin-class-composition
13+
---
14+
Self-types are a way to declare that a trait must be mixed into another trait, even though it doesn't directly extend it. That makes the members of the dependency available without imports.
15+
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+
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+
```tut
20+
trait User {
21+
def username: String
22+
}
23+
24+
trait Tweeter {
25+
this: User => // reassign this
26+
def tweet(tweetText: String) = println(s"$username: $tweetText")
27+
}
28+
29+
class VerifiedTweeter(val username_ : String) extends Tweeter with User { // We mixin User because Tweeter required it
30+
def username = s"real $username_"
31+
}
32+
33+
val realBeyoncé = new VerifiedTweeter("Beyoncé")
34+
realBeyoncé.tweet("Just spilled my glass of lemonade") // prints "real Beyoncé: Just spilled my glass of lemonade"
35+
```
36+
37+
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`).

0 commit comments

Comments
 (0)