Skip to content

Commit 8050e06

Browse files
committed
Rewrote self-type tour
1 parent 7ab45eb commit 8050e06

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+
When writing extensible code, it can be useful to declare a self-type as a means of dependency injection.
15+
16+
To use a self-type in a trait, write an identifier, the type of another trait to mix in, and a right fat arrow (e.g. `someIdentifier: SomeOtherTrait =>`).
17+
```tut
18+
trait User {
19+
def username: String
20+
}
21+
22+
trait Tweeter {
23+
this: User => // reassign this
24+
def tweet(tweetText: String) = println(s"$username: $tweetText")
25+
}
26+
27+
class VerifiedTweeter(val username_ : String) extends Tweeter with User{
28+
def username = s"real $username_"
29+
}
30+
31+
val realBeyoncé = new VerifiedTweeter("Beyoncé")
32+
realBeyoncé.tweet("Just spilled my glass of lemonade") // real Beyoncé: Just spilled my glass of lemonade
33+
```
34+
35+
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`).
36+
37+
Whenever a trait needs to mix-in another trait, a self-type can be used to bring the other trait's members into scope.

0 commit comments

Comments
 (0)