如何习惯从Scala/Lift中处理空检查? [英] How do I idiomatically handle null checks from within Scala/Lift?

查看:51
本文介绍了如何习惯从Scala/Lift中处理空检查?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使Box和Option单子的流行,我们仍然必须在这里和那里检查null值.到目前为止,我想出的最好办法就是使用Box#!方法:

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("")

是否有更好的方法可以做到这一点?我尝试使用Box的apply方法:

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.

推荐答案

我不知道Box是关于什么的.但是这里有一个使用Option的简单示例:

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

这篇关于如何习惯从Scala/Lift中处理空检查?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆