我想檢查構造函數參數並拒絕構造拋出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 = [email protected]
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
是的。它必須是可變的。@ Debilski – Optimight
從哪裏可以瞭解有關copy(length = l)函數/運算符的更多信息?任何文章/鏈接/ pdf? – Optimight
@ user1417244你可以使用'scalac -Xprint:typer'。例如:'echo'case class Rectangle(length:Double,width:Double)'> test.scala && scalac -Xprint:typer test.scala'。你會得到這個:'def copy(length:Double = length,width:Double = width):Rectangle = new Rectangle(長度,寬度)' – senia