score:2

Accepted answer

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.


Related Query

More Query from same tag