How to extend a superclass and call a method or lazy val in superclass constructor parameters

时间:2016-04-15 14:56:10

标签: scala

I am trying to figure out how to do any sort of computation, method call, etc. in calling superclass constructor parameters.

Here is an example: I am extending RuntimeException and want to perform a computation on my parameters in order to determine the superclass parameters. Specifically, I want to figure out what my highest priority error is and pass that to the RuntimeException message. I believe there is no other way to set RuntimeException's message string except through its constructor.

myErrors is a list of tuples of (severity, messageString)

class MyRunTimeException(val myErrors: List[Tuple2[Int,String]]) extends RuntimeException(myErrors.highestSeverityError) {
  lazy val highestSeverityError = myErrors.sortBy( tup => tup._1 ).head._2
}

Compiler says it can't resolve "highestSeverityError" in the superclass constructor call.

1 个答案:

答案 0 :(得分:3)

You cannot use instance methods before superclass is initialized. Something like this should work for you I guess:

object MyRunTimeException {
  def mostSevere(errs: List[(Int, String)]) = errs.sortBy(_._1).head._2
}
class MyRunTimeException(val errs: List[(Int, String)])
   extends RuntimeException(MyRunTimeException.mostSevere(errs))