如何在 Scala/Lift 中惯用地处理 null 检查?

发布于 2024-09-28 14:51:34 字数 509 浏览 1 评论 0原文

即使 Box 和 Option monad 很流行,我们仍然必须到处检查空值。到目前为止我想出的最好的方法是使用 Box#!方法:

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

有更好的方法吗?我尝试使用 Box 的 apply 方法:

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

但是编译器抱怨对重载定义的引用不明确,具体来说:

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

我不确定为什么会发生这种情况,但我希望有一种更短、更简洁的方式来表达“给我这个字符串的值,或者只是“”我正在考虑使用tryo,但认为在可以避免的情况下处理异常是浪费的。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风吹短裙飘 2024-10-05 14:51:34

我不知道Box是做什么的。但这里有一个使用 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

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文