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? 回答1: 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: