简体   繁体   中英

Can the stackable trait pattern be used with singleton objects?

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")

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM