我想检查构造函数参数并拒绝构造 throwing IllegalArgumentException,以防参数集无效(值不符合预期的约束)。在修改对象时设置相同的参数集时,同样的检查应该起作用。如何在 Scala 中编写代码?
scala> class Rectangle (var Length:Double, var Width:Double){
| if (Length <0)
| throw new IllegalArgumentException("The Length must be Non-negative")
| if (Width <0)
| throw new IllegalArgumentException("The Width must be Non-negative")
| def setLength(l:Double) = Length = l
| }
defined class Rectangle
scala> var R = new Rectangle (-9, -9)
java.lang.IllegalArgumentException: The Length must be Non-negative
at Rectangle.<init>(<console>:9)
scala> var R = new Rectangle (0, -9)
java.lang.IllegalArgumentException: The Width must be Non-negative
at Rectangle.<init>(<console>:11)
scala> var R = new Rectangle(9, 9)
R: Rectangle = Rectangle@1590164
scala> R.Length
res7: Double = 9.0
scala> R.Width
res8: Double = 9.0
scala> R.setLength(18)
scala> R.Length
res10: Double = 18.0
scala> R.setLength(-9)
// R.setLength should not the set the Length to -9. **************************
scala> R.Length
res12: Double = -9.0