NNamed
NNamed

Reputation: 727

Using stackable trait with singleton object

my case is a bit similar to this question:

Can the stackable trait pattern be used with singleton objects?

but with small difference. What I have can be simplified to the below form:

abstract class Pr {
  def pr()
}

trait PrePostPr extends Pr {
  var NUMERIC_VAR: Int = _
  abstract override def pr() {
    NUMERIC_VAR = 5 // number is being extracted eg. from conf file
    super.pr()
  }
}

Now I would really like to have a singleton object that will check the constant and depending on it would take some further action in a following way:

class ImplPr extends Pr with PrePostPr {
  def pr() = if(NUMERIC_VAR > 5) println("Foo") else println("Bar")
}

object Foo extends ImplPr
Foo.pr()

Unfortunatelly, the above code does not compile - I get:

method pr needs `override' modifier

Is there any workaround to make this solution work?

Upvotes: 0

Views: 213

Answers (1)

devkat
devkat

Reputation: 1644

It would work if you move NUMERIC_VAR to a different trait:

  trait NumericVarHolder {
    var NUMERIC_VAR: Int = _
  }

  abstract class Pr {
    def pr()
  }

  trait PrePostPr extends Pr {
    self: NumericVarHolder =>
    abstract override def pr() {
      NUMERIC_VAR = 5 // number is being extracted eg. from conf file
      super.pr()
    }
  }

  class ImplPr extends Pr with NumericVarHolder {
    def pr() = if(NUMERIC_VAR > 5) println("Foo") else println("Bar")
  }

  object Foo extends ImplPr

Upvotes: 2

Related Questions