How do I idiomatically handle null checks from within Scala/Lift?
Asked Answered
S

1

11

Even with the prevalence of the Box and Option monads, we still have to check for null values here and there. The best I've come up with so far is by using the Box#!! method:

(Box !! possiblyNull).map(_.toString).openOr("")

Is there a better way to do this? I tried using Box's apply method:

Box(possiblyNull).map(_.toString).openOr("")

But the compiler complained of an ambiguous reference to an overloaded definition, specifically:

[InType,OutType](value: InType)
(pf: PartialFunction[InType,OutType])net.liftweb.common.Box[OutType]

I'm not sure why that's happening, but I was hoping there would be a shorter, more concise way of saying "Give me the value of this string, or just "". I was considering using tryo, but thought it wasteful to deal with an exception when it could be avoided.

Spiritual answered 20/10, 2010 at 14:7 Comment(0)
K
19

I don't know what Box is about. But here goes a simple example using Option:

scala> val str1:String="abc"
str1: String = abc

scala> val str2:String=null
str2: String = null

scala> Option(str1).getOrElse("XXX")
res0: String = abc

scala> Option(str2).getOrElse("XXX")
res1: String = XXX
Kirkwood answered 20/10, 2010 at 18:39 Comment(2)
Wow, that's much easier.. thanks. Also, Box is the Lift framework's re-vamping of Option. Instead of Option's two subclasses, it has three: Full, Empty, and Failure.Spiritual
That sounds a like scala-lang.org/archives/downloads/distrib/files/nightly/docs/…Kirkwood

© 2022 - 2024 — McMap. All rights reserved.