int的标量句柄为空

问题描述 投票:0回答:2

我有下面的代码

   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
    }
scala pattern-matching
2个回答
0
投票

如果数字是选项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的更多信息>


0
投票

如果您发布的numOption[String],则说明您有4种不同的条件需要考虑:

© www.soinside.com 2019 - 2024. All rights reserved.