Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")
like image 289
srparish Avatar asked Sep 21 '11 12:09

srparish


1 Answers

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.

like image 199
axel22 Avatar answered Oct 28 '22 12:10

axel22