scala - 在 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。想法?谢谢!
解决方案
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
}
推荐阅读
- android - 为什么我得到 com.fasterxml.jackson.databind.exc.InvalidDefinitionException?
- python - 需要 DataBricks Python 单元测试错误帮助
- google-bigquery - 使用 json 文件创建表
- sql - 正则表达式 SQL BigQuery 获取 '_' 之间的数字
- python-3.x - Mongodb查询没有响应
- ssis - SSIS - 插入前的数据流目标验证
- vite - v-bind:class 在构建和刷新后不起作用
- laravel - Laravel - errno:150 外键约束形成错误 - 一对多关系
- c# - 为不同的孩子丰富基类
- aws-glue - 当我尝试使用 python 运行 Glue 作业来关系化数组和结构数据时