user4399595
user4399595

Reputation:

Scala class - required property

I would like to define trait that has const property, for example:

trait InitialTest {
    // property would be set here or somewhere else, let's call it typeNumber

   override def toString = typeNumber.toString
}

then I would like to set this value for each implementation like:

case class InitialTest1 extends InitialTest {
   // set value here like typeNumber = 4
}

For each toString function would use impelemetation from trait. Do you know how can I acheive it?

Upvotes: 0

Views: 102

Answers (1)

Mateusz Kubuszok
Mateusz Kubuszok

Reputation: 27535

The easiest way of achieving it, that I see is:

trait MyTrait {

  val myProperty: X // abstract property

  override def toString: String = myProperty.toString
}

It would force implementation of the property:

class Impl extends MyTrait {

  val myProperty = new X // without that line it doesn't compile
}

From there on, one might complicate design further e.g. by splitting the trait with the property from the trait overriding toString with a cake pattern (though I'd be vary about it).

Upvotes: 2

Related Questions