Sonson
Sonson

Reputation: 1139

How to use Box with Java null values

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.

Upvotes: 1

Views: 691

Answers (3)

omnomnom
omnomnom

Reputation: 9139

You can use Box.legacyNullTest. This method encapsulates any object in a Box in a null-safe manner:

def legacyNullTest[T](in: T): Box[T] = in match {
  case null => Empty
  case _ => Full(in)
}

Box returned from legacyNullTest can be later used as usual in for comprehensions or in pattern matching:

for {
  fragment <- Box.legacyNullTest(uri.getFragment)
yield {
  doSth(fragment)
}

or

Box.legacyNullTest(uri.getFragment) match {
  case Full(fragment) =>
    doSth(fragment)
  case _ =>
    log.error("Missing fragment part")
    doSthElse
}

Upvotes: 1

leedm777
leedm777

Reputation: 24032

@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

Upvotes: 5

Spencer Uresk
Spencer Uresk

Reputation: 3710

Similar to Scala's Option, you can simply call Box() and pass in the value that may or may not be null, and you'll get a Box object that can be used normally. For example:

Box(javaobject.findThing(xyz)) match {
    case Full(thing) => thing.doAnotherThing()
    case _ => warn("Value not found.")
}

Upvotes: 1

Related Questions