【发布时间】:2020-06-09 05:11:44
【问题描述】:
我有以下代码
val num = (json \ "somenum").asOpt[String] => no restriction here can take as opt[int] also but need to handle null
var numNew: Int = null
if (num.isEmpty || num < 100) {
numNew = new Random().nextInt(SomeValue)
}
else {
numNew = Integer.parseInt(num.toString)
}
我想实现它的大小写/模式匹配代码。我试过但小于< 不起作用
val output= num match {
case None => new Random().nextInt(100)
case Some(x) => Integer.parseInt(num.toString)
case Some(x)< 0 => new Random().nextInt(100) ==> throws error < not found
}
【问题讨论】:
-
你是什么意思不起作用?不是在编译吗?案件的顺序很重要。有优先顺序。例如。 stackoverflow.com/q/7097107/259889
-
@jwvh 我该怎么写..你能帮忙吗?
-
Option[A]的运算符<未定义。您可以这样修复它:case Some(x) if x < 0 => new Random().nextInt(100),但仅适用于具有运算符<的类型。Int有。 -
1) 你不应该比较 String 和 Int 并且 2) 你应该改变 case 的顺序