我是一个Lift初学者,经常编写这样的代码:我使用Java方法返回一个对象或者null找不到值.所以我需要检查空值:
val value = javaobject.findThing(xyz)
if(value != null) {
value.doAnotherThing()
} else {
warn("Value not found.")
}
Run Code Online (Sandbox Code Playgroud)
我可以使用Box概念更短地编写此代码吗?我已经阅读了有关Box概念的Lift-Wiki文档,但我不明白如何将它与Java null值一起使用.
@TimN是对的,你可以Box(value)用来创建Box一个可能的null值,但你会得到一个弃用警告.
scala> val v: Thing = null
v: Thing = null
scala> Box[Thing](v)
<console>:25: warning: method apply in trait BoxTrait is deprecated: Use legacyNullTest
Box[Thing](v)
Run Code Online (Sandbox Code Playgroud)
虽然你可以使用Box.legacyNullTest,如果这是你正在做的事情,那么我会坚持使用标准库Option.
Option(javaobject.findThing(xyz)) match {
case Some(thing) => thing.doAnotherThing()
case _ => warn("Value not found.")
}
Run Code Online (Sandbox Code Playgroud)
如果你需要一个Box传递,Option将自动转换为Box:
scala> val b: Box[Thing] = Option(v)
b: net.liftweb.common.Box[Thing] = Empty
Run Code Online (Sandbox Code Playgroud)