I use a Java method that returns an object or null
if a value was not found. So I need to check for null values:
val value = javaobject.findThing(xyz)
if(value != null) {
value.doAnotherThing()
} else {
warn("Value not found.")
}
Can I write this code shorter with the Box concept? I have read the Lift-Wiki-documentation about the Box concept, but I don't understand how to use it with Java null values.
@TimN is right, you could use Box(value)
to create a Box
from a possibly null
value, but you'll get a deprecation warning.
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)
While you could use Box.legacyNullTest
, if this is what you're doing, then I would just stick with the standard library and use Option
.
Option(javaobject.findThing(xyz)) match {
case Some(thing) => thing.doAnotherThing()
case _ => warn("Value not found.")
}
And if you needed a Box
to pass around, Option
will automagically convert to a Box
:
scala> val b: Box[Thing] = Option(v)
b: net.liftweb.common.Box[Thing] = Empty