Self-types
trait User {
def username: String
}
trait Tweeter {
this: User => // reassign this
def tweet(tweetText: String) = println(s"$username: $tweetText")
}
class VerifiedTweeter(val username_ : String) extends Tweeter with User { // We mixin User because Tweeter required it
def username = s"real $username_"
}
val realBeyoncé = new VerifiedTweeter("Beyoncé")
realBeyoncé.tweet("Just spilled my glass of lemonade") // prints "real Beyoncé: Just spilled my glass of lemonade"
Are a way to declare that a trait must be mixed into another trait, even though it doesn’t directly extend it.
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.
Self-types → are a → Scala Unified types.