Scala 为 int 处理 null

Scala handle null for int

我有以下代码

   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)
    }

我想实现它 case/pattern 匹配 code.I 尝试过但小于 < 不工作

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
    }

如果num是选项Int,你可以这样写:

val num: Option[Int] = (json \ "somenum").asOpt[Int]
var numNew: Int = num.filter(x => x < 0).getOrElse(new Random().nextInt(100))

在这些代码中,如果 num 是 NoneSome 且 int 小于零,它将使用随机 Int。

阅读更多关于 Option scala documentation

如果 num 是一个 Option[String],正如您发布的那样,那么看起来您有 4 个不同的条件需要考虑:

  1. numNone
  2. numSome(s)s 不是数字
  3. numSome(s) 其中 s 是一个数字 >= 100
  4. numSome(s) 其中 s 是一个 < 100
  5. 的数字

这在某种程度上取决于你想如何处理这些,但我很想从 fold() 开始,然后从那里开始。

val num :Option[String] = . . .

val isNum = "(\d+)".r
num.fold("empty"){
  case isNum(digits) =>
    val n = digits.toInt
    if (n < 100) "less than 100"
    else "too big"
  case _ => "not digits"
}

测试:

val num :Option[String] = None         //"empty"
val num :Option[String] = Some("9X9")  //"not digits"
val num :Option[String] = Some("919")  //"too big"
val num :Option[String] = Some("99")   //"less than 100"

可以修改 isNum 正则表达式以解释负 and/or 小数。


如果numNonenumSome(notNumber)之间没有区别(也就是说你不关心区别)那么事情就可以了稍微简化了。

num.flatMap(s => util.Try(s.toInt).toOption) match {
  case Some(n) if n < 100 => s"$n is less than 100"
  case Some(n)            => s"$n is too big"
  case _                  => "not a number"
}