How to check constructor arguments and throw an exception or make an assertion in a default constructor in Scala?
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? missingfaktor In Scala, the whole body of the class is your primary constructor, so you can add your validation logic there. scala> class Foo(val i: Int) { | if(i < 0) | throw new IllegalArgumentException("the number must be non-negative.") | } defined class Foo scala> new Foo(3) res106: Foo = Foo@3bfdb2 scala> new Foo(-3) java.lang.IllegalArgumentException: the number must be