I would like to check constructor arguments and refuse to construct throwing IllegalArgumentException
in case the arguments set is not valid (the values don't fit in expected constraints). How to code this in Scala?
Scala – How to check constructor arguments and throw an exception or make an assertion in a default constructor in Scala
assertconstructorexceptionscala
Related Topic
- Java – Why do this() and super() have to be the first statement in a constructor
- Javascript – Use of .apply() with ‘new’ operator. Is this possible
- Scala – the difference between Scala’s case class and class
- Python – How to catch and print the full exception traceback without halting/exiting the program
- C# – Call one constructor from another
- Scala – the formal difference in Scala between braces and parentheses, and when should they be used
Best Answer
In Scala, the whole body of the class is your primary constructor, so you can add your validation logic there.
Scala provides a utility method
require
that lets you write the same thing more concisely as follows:A better approach might be to provide a factory method that gives a
scalaz.Validation[String, Foo]
instead of throwing an exception. (Note: requires Scalaz)