首页 > 解决方案 > 在 scala 中使用布尔值评估选项

问题描述

我是 Scala 的新手,我在无法修改的 Java 中现有的 JPA 代码之上编写了一些代码(因此在这里重写对象不是解决方案)。数据库中的一些值是空的,所以不出所料,当我尝试做类似的事情时

if (myObject.nullAttributeTypeInt > someInt) {...}

我得到一个空指针错误。如果我尝试这样的事情:

if(Option(myObject.nullAttributeTypeInt).getOrElse(1) > someInt) {...}

我收到一个编译错误,因为条件的前件是 Any 类型,并且没有在其上定义布尔运算符。

我认为有一些聪明/简洁的方法可以使用 Option 来处理这个问题,但我找不到现成的答案。我可以做类似的事情

Option(myObject.nullAttributeTypeInt).getOrElse(1).toString.toInt

但这感觉很hacky。想法?谢谢!

标签: scala

解决方案


If the condition fails because the type of myObject.nullAttributeTypeInt is java.lang.Integer then you have to convert it to Scala's Int explicitly or implicitly.

You can use Int.unbox to unwrap Java's Integer:

Option(myObject.nullAttributeTypeInt).fold(1)(Int.unbox) 

Or Scala can also unbox automatically if it knows the result must be Scala's Int:

Option(myObject.nullAttributeTypeInt).fold(1)(i => i: Int)

Alternative syntax with match:

Option(myObject.nullAttributeTypeInt) match {
  case Some(javaInt) => javaInt: Int
  case None => 1
}

推荐阅读