【问题标题】:Scala handle null for intScala 为 int 处理 null
【发布时间】: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)
    }

我想实现它的大小写/模式匹配代码。我试过但小于&lt; 不起作用

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] 的运算符 &lt; 未定义。您可以这样修复它:case Some(x) if x &lt; 0 =&gt; new Random().nextInt(100),但仅适用于具有运算符 &lt; 的类型。 Int 有。
  • 1) 你不应该比较 String 和 Int 并且 2) 你应该改变 case 的顺序

标签: scala pattern-matching


【解决方案1】:

如果 numOption[String],正如您所发布的,那么您似乎需要考虑 4 个不同的条件:

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

这在某种程度上取决于您希望如何处理每一个问题,但我很想从 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 正则表达式可以修改以解释负数和/或小数。


如果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"
}

【讨论】:

  • 如果输入小于 0 或为空,我想创建新的随机数,否则应该分配输入的任何内容
【解决方案2】:

如果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。

阅读更多关于Optionscala documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 2014-02-12
    相关资源
    最近更新 更多