2

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?

4

1 回答 1

5

您可以使用早期初始化程序:

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 );

从老式的词法作用域的角度来看,它甚至可以编译是很奇怪的。但是编译它会做,它会做你想做的事!不过,它是否比您的解决方案“更好”是一个品味问题。

于 2013-05-23T20:38:03.260 回答