Frage

I have something like this:

abstract class RunnerBase { def printErrorAndBreak = ... }

object Runner1 extends RunnerBase {
  breakable {
    doSomething
    if (cond1) printErrorAndBreak(...)
  }
}

object Runner2 extends RunnerBase {
  breakable {
    if (cond1) printErrorAndBreak(...)
    something else
  }
}

I'd like to move the breakable { ... } part into RunnerBase so that Runner1 and Runner2 looked like this instead:

object Runner1 extends RunnerBase {
  doSomething
  if (cond1) printErrorAndBreak(...)
}

object Runner2 extends RunnerBase {
  if (cond1) printErrorAndBreak(...)
  something else
}

Is this even possible? Or is my only way to wrap the subobject logic in, say, a run method?


UPDATE: Based on the accepted answer (and regardless of the comments), for the sake of robustness and simplicity, I've decided to go with this:

class RunnerBase { def run = breakable _ }
class Runner1 { run { doSmth; if (?) printErrorAndBreak } }
class Runner2 { run { doSmth; if (?) printErrorAndBreak } }

Not perfect because there's still the run { ... } repetition, but at least breakable and break are encapsulated in RunnerBase.

War es hilfreich?

Lösung

How about DelayedInit?

import scala.util.control.Breaks._

trait BreakInit extends DelayedInit {
  def delayedInit(body: => Unit) {
    breakable {body}
  }
}

class MyClass extends BreakInit {
  println("Hello World")
  break()
  println("Error - should not be reachable")
}

val a = new MyClass

In this case, we've created a trait BreakInit that inherits from DelayedInit, which overrides the delayedInit method to call the constructor within a breakable block. MyClass's constructor is then rolled up into a function, and passed to the delayedInit method. As @som-snytt points out, the DelayedInit magic only affects class constructors, not trait constructors.

However, I'd advise a note of caution when using DelayedInit. It involves some reasonably deep compiler magic, and magic always comes with a price. Personally, I'd tend to prefer your original approach, as there's less magic involved.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top