Scala 自身类型(self-type) 解析

Scala 有一个自身类型(self-type) 的东西,由来已久,居然今天才发现。如果一个类或 trait 指明了 self-type 类型(包括类和特质),它的子类型或是对象也必须是相应的类型。它产生的效果与继承(或 mixin) 颇有几分相似。self-type 的语法是 this 的别名: 某一类型(class 或 trait), 直接看一个例子:

class User(val name: String)
 
trait Tweeter {
  this: User =>  //这个表示 Tweeter 本身也必须是一个 User,它的子类型必须想办法符合这一要求
  def tweet(tweetText: String) = {
    println(s"$name: $tweetText")
  }
}
 
class VerifiedTweeter(val username: String)
  extends User(username) with Tweeter {  //Tweeter 要求这个类必须是一个 User, 所以需要继承自 User 类
}
 
val v = new VerifiedTweeter("Yanbin")
v.tweet("Hello")
上面  this: User =>  中的  this  只是一个别名,可以是  self  或任何有效标识(如   abc: User ),这里使用  this  等于未指定别名,与原本的 this 重叠了。如果声明为非  this  的话则可以这么用  阅读全文 >>

猜你喜欢

转载自blog.csdn.net/kypfos/article/details/79324088