You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Scala的require方法中使用条件逻辑?复数类验证示例

修正Scala中ComplexNum类的require条件逻辑

你现在的问题出在require的条件写反啦!Scala里的require方法是当传入的条件为false时,才会抛出IllegalArgumentException。你原来写的条件(real==0 && imaginary==0),意味着只有当两个值都为0时条件才成立(返回true),这时候不会抛出错误——完全和你想要的效果反过来了!

修正后的代码

你只需要把条件改成「至少有一个值不为0」就行,有两种等价的写法:

写法一:使用逻辑或(更直观)

class ComplexNum(val real: Int, val imaginary: Int) {
  require(real != 0 || imaginary != 0, "Real or Imaginary, either any one should have value")
}

写法二:对原条件取反

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) // 条件为true,正常实例化,无错误
  val complexNumber2= new ComplexNum(0,1) // 条件为true,正常实例化,无错误
  val complexNumber3= new ComplexNum(1,0) // 条件为true,正常实例化,无错误
  val complexNumber4= new ComplexNum(0,0) // 条件为false,抛出IllegalArgumentException,符合预期
}

这样就完全符合你想要的效果啦!

内容的提问来源于stack exchange,提问作者prady

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:32:58