Can the stackable trait pattern be used with singl

2019-02-16 21:06发布

I'd like to use the stackable trait pattern with singleton objects, but i can't seem to find how to make the compiler happy:

abstract class Pr {
  def pr()
}

trait PrePostPr extends Pr {
  abstract override def pr() {
    println("prepr")
    super.pr()
    println("postpr")
  }
}

object Foo extends Pr with PrePostPr {
  def pr() = println("Foo")
}

Trying to evaluate this in the repl produces the following error:

<console>:10: error: overriding method pr in trait PrePostPr of type ()Unit;
 method pr needs `override' modifier
         def pr() = println("Foo")

1条回答
仙女界的扛把子
2楼-- · 2019-02-16 21:58

It can, but like this:

abstract class Pr {
  def pr()
}

trait PrePostPr extends Pr {
  abstract override def pr() {
    println("prepr")
    super.pr()
    println("postpr")
  }
}

class ImplPr extends Pr {
  def pr() = println("Foo")
}

object Foo extends ImplPr with PrePostPr

The implementation has to be present in one of the superclasses/supertraits. The abstract modification trait has to come after the class/trait with the implementation in the inheritance list.

查看更多
登录 后发表回答