Early return from Scala constructor

I am writing a constructor for my "main" class. The first thing he does is invoke a method to use commons-cli to parse the command line. If the parseOptions method returns false, an error has occurred and the constructor should exit.

I tried to write the following code

 if (!parseOptions(args)) return 

but the compiler complains that I have a definition of "Definition of an External Operator".

The call to System.exit(1) ends or inverts the boolean value (and puts the rest of my logic in the if , is there any way to return the β€œearly” from the constructor?

I believe that the parseOptions method could throw an IllegalArgumentException and catch it in my Main object.

Thanks.

+6
constructor scala exit
source share
3 answers

is there any way to return "early" from the constructor

Not. But in your case, it sounds like a bad design, anyway.

If parseOptions returns false, an error has occurred

In this case, the constructor should throw an exception, and not return normally.

+11
source share

Do not try to make an early / premature return, this makes your code more complex, as the side effects of the return can be difficult to understand. Instead, use an exception to report that something is wrong.

You can use require in the constructor. This is not coming back. But it seems that throwing an exception is really better suited to his situation.

How in:

 class MyTest( private var myValue: Int ){ require(myValue > 0) // Connected to constructor } defined class MyTest scala> val x = new MyTest(10) x: MyTest = MyTest@49ff4282 scala> val y = new MyTest(-10) java.lang.IllegalArgumentException: requirement failed at scala.Predef$.require(Predef.scala:133) 
+12
source share

The constructor must either complete completely or abort (throw an exception). Everything else leaves your object β€œhalf built” and therefore impossible to reason about.

If in your case the object is valid, even if parseOptions failed, you can change the condition and continue:

 if (parseOptions(args)) { // rest of constructor } 
+4
source share

All Articles