Janek Bogucki
Janek Bogucki

Reputation: 5123

How to supply transformed params to superclass constructor while avoiding inline computations with Scala

This is my current unsatisfactory solution to the problem of manipulating the values passed to the subclass constructor before passing onto the superclass constructor,

class MissingItemsException(items: Set[String], itemsCategory: String)
  extends RuntimeException(MissingItemsException.makeMessage(items, itemsCategory))

private object MissingItemsException {

  private def makeMessage(items: Set[String], itemsCategory: String): String = {
    /* Format set as ['α','β','γ'] */
    val Items = items mkString ("['", "','", "']")
    "the following items %s were missing from '%s'" format (items, itemsCategory)
  }

}

Is there a way of factoring out the transformation so that the transformation code remains close to the point of use while keeping the code legible?

Upvotes: 2

Views: 88

Answers (1)

Steve Waldman
Steve Waldman

Reputation: 14073

You can use an early initializer:

class MissingItemsException(items: Set[String], itemsCategory: String) extends {
  val customMessage = {
    val Items = items mkString ("['", "','", "']")
    "the following items %s were missing from '%s'" format (items, itemsCategory)
  }
} with RuntimeException( customMessage );

It's bizarre that it even compiles, from an old-fashioned lexical scoping perspective. But compile it does, and it does what you want! Whether it's "better" than your solution is a matter of taste, though.

Upvotes: 5

Related Questions