How do I idiomatically handle null checks from Scala / Lift?

Even with the predominance of Box and Option monads, we still need to check for null values ​​here and there. The best I've come up with so far is to use Box # !! Method:

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

Is there a better way to do this? I tried using the Box application method:

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

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

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

I'm not sure why this happened, but I was hoping there would be a shorter and more concise way of saying, β€œGive me the meaning of this line or simply.” I was considering using tryo, but thought it was wasteful to handle the exception when it could be avoided.

+7
scala lift
source share
1 answer

I do not know what Box is. But here is a simple example using the 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 
+11
source share

All Articles