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?
I would like to check constructor arguments and refuse to construct throwing IllegalArgumentException in
Share
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
requirethat 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)