trait中super调用动态绑定

class Root{
  def hello(){
    println("Hello,Root!")
  }
}

class SubA extends Root{
  override def hello() {
    println("Hello,SubA!")
  }
}


trait D extends Root{
  def traitHello(){
    super.hello();
  }
}


对于trait D而言,虽然其扩展了class Root,但是super.hello()并不是指Root的hello方法 ,而是在D被混入后的目标类的hello.

SCALA编译原文描述不严格:

The Doubling trait has two funny things going on. The first is that it declaresa superclass, IntQueue. This declaration means that the trait can only bemixed into a class that also extends IntQueue. Thus, you can mix Doublinginto BasicIntQueue, but not into Rational.

因为原文中 IntQueue是抽象类,所以无法展示 Doubling对 IntQueue的super调用,我们这里的这个例子,Root不是抽象类,本身也可以直接混入D,而不仅仅是只有子类才可以混入。

    val e = new Root with D
    e.traitHello()
  
    val f = new SubA with D
    f.traitHello()

输出:

Hello,Root!
Hello,SubA!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值