Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在scala require方法中使用条件逻辑?_Scala - Fatal编程技术网

如何在scala require方法中使用条件逻辑?

如何在scala require方法中使用条件逻辑?,scala,Scala,我的例子是: class ComplexNum(val real:Int,val imaginary:Int) { require((real==0 && imaginary==0 ),"Real or Imaginary, either any one should have value") } 我正在努力实现的目标如下: object main extends App { val complexNumber1= new ComplexNum(1,1) //Sh

我的例子是:

class ComplexNum(val real:Int,val imaginary:Int) {

  require((real==0 && imaginary==0 ),"Real or Imaginary, either any one should have value") 

}
我正在努力实现的目标如下:

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
}
目前我在前3个条件下得到错误,在第4个条件下没有错误


有人能帮我理解上述例子所要求的方法和正确的解决方案吗

您已经编写了
require
方法,因为
real
virtual
变量应始终为0因此,如果传递除0以外的任何整数值,则会出现以下错误

java.lang.IllegalArgumentException:需求失败:实数或虚数,任何一个都应该有值

如果您想要
实的或虚的,任何一个都应该有值
,那么您应该将
require
方法定义为

class ComplexNum(val real:Int,val imaginary:Int) {
  require((Option(real).isDefined && Option(imaginary).isDefined),"Real or Imaginary, either any one should have value")
}

您已经编写了
require
方法,因为
real
virtual
变量应始终为0因此,如果传递除0以外的任何整数值,则会出现以下错误

java.lang.IllegalArgumentException:需求失败:实数或虚数,任何一个都应该有值

如果您想要
实的或虚的,任何一个都应该有值
,那么您应该将
require
方法定义为

class ComplexNum(val real:Int,val imaginary:Int) {
  require((Option(real).isDefined && Option(imaginary).isDefined),"Real or Imaginary, either any one should have value")
}

逻辑反转的一个简单例子

require(!(real==0 && imaginary==0),"Real or Imaginary, either any one should have value")
。。。也可以表示为

require(real!=0 || imaginary!=0,"Real or Imaginary, either any one should have value")

逻辑反转的一个简单例子

require(!(real==0 && imaginary==0),"Real or Imaginary, either any one should have value")
。。。也可以表示为

require(real!=0 || imaginary!=0,"Real or Imaginary, either any one should have value")

您将require方法写成实变量和虚变量应始终为0,我以其他方式理解require方法。您将require方法写成实变量和虚变量应始终为0,我以其他方式理解require方法。我尝试测试提供的解决方案,所有条件都会通过。我不知道你想要避免在真实和想象中都使用0:)对不起,如果我没有清楚地解释这个场景,我不理解是我的错误。jwh已经理解并给了您正确的答案:)我尝试测试提供的解决方案,它在所有条件下都通过了。我不知道您想要避免在真实和虚拟中都使用0:)对不起,如果我没有清楚地解释该场景,我不理解是我的错误。jwh已经理解并给了您正确的答案:)