Can the stackable trait pattern be used with singleton objects?

拥有回忆 提交于 2019-12-01 00:58:01

问题


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:


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.



来源:https://stackoverflow.com/questions/7499680/can-the-stackable-trait-pattern-be-used-with-singleton-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!