Reputation: 593
My Example :
class ComplexNum(val real:Int,val imaginary:Int) {
require((real==0 && imaginary==0 ),"Real or Imaginary, either any one should have value")
}
what I am trying to achieve is commented as below,
object main extends App {
val complexNumber1= new ComplexNum(1,1) //Should Not throw an error
val complexNumber2= new ComplexNum(0,1) //Should Not throw an error
val complexNumber3= new ComplexNum(1,0) //Should Not throw an error
val complexNumber4= new ComplexNum(0,0) //Should throw an error
}
Currently I am getting error for first 3 conditions and no error for 4th condition.
Can someone please help me to understand the require method with above example with correct solution?
Upvotes: 0
Views: 318
Reputation: 51271
A simple case of logic inversion.
require(!(real==0 && imaginary==0),"Real or Imaginary, either any one should have value")
... can also be expressed as ...
require(real!=0 || imaginary!=0,"Real or Imaginary, either any one should have value")
Upvotes: 1
Reputation: 41987
You have written require
method as real
and imaginary
variables should always be 0. So if you pass any integer value other than 0 then you would have following error
java.lang.IllegalArgumentException: requirement failed: Real or Imaginary, either any one should have value
If you want Real or Imaginary, either any one should have value
then you should define require
method as
class ComplexNum(val real:Int,val imaginary:Int) {
require((Option(real).isDefined && Option(imaginary).isDefined),"Real or Imaginary, either any one should have value")
}
Upvotes: 1