Azeli
Azeli

Reputation: 748

Scala - methods conditionally implemented in trait?

I am looking for the cleanest way to allow user to choose implementation of a method without repeating myself. in the situation below, each of the subclasses put together a greeting in XML with parameters from the specific class. thus the method toXML is declared abstract in the trait. What I want, however is to check if a _generalMessage was passed in in the construction of the class, and if so, use a general XML greeting common to all implementations of Greeting, e.g. <Message>_generalMessage</Message>. I know I can just pattern match on the existence of _generalMessage in each of the implementations of Greeting, but I am curious if there is a more elegant way.

trait Greeting {
  protected var foo = //...
  protected var _generalMessage: Option[Srting] = None
  //...
  //public API
  def generalMessage: String = _generalMessage match {case Some(x) => x; case None =>""
  def generalMessage_=(s: String) {_generalMessage = Some(s)}

  protected def toXML: scala.xml.Node

}

class specificGreeting1 extends Greeting {
  // class implementation
  def toXML: scala.xml.Node = <//a detailed XML with values from class specificGreeting1>
}
// multiple other specificGreeting classes

Upvotes: 1

Views: 149

Answers (1)

Dima
Dima

Reputation: 40510

Make toXML final, and define it in the base trait:

  final def toXML = _generalMessage.fold(specific message) { m =>
       <Message>m</Message>
  }

Then define specificMessage in your subclasses to be what you currently have as toXML.

Upvotes: 2

Related Questions