Skip to content

Commit 7fa2b19

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

File tree

2 files changed

+35
-123
lines changed

2 files changed

+35
-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: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
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+
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`).

0 commit comments

Comments
 (0)