如何在scala中编写一个正确的null安全合并运算符?

psp*_*psp 23 scala coalescing

看到像这样一个涉及恐怖的问题的答案显示就像试图抓住NPE并从堆栈轨迹中挖掘出受损的名称,我问这个问题所以我可以回答它.

欢迎评论或进一步改进.

psp*_*psp 37

像这样:

case class ?:[T](x: T) {
  def apply(): T = x
  def apply[U >: Null](f: T => U): ?:[U] =
    if (x == null) ?:[U](null)
    else ?:[U](f(x))
}
Run Code Online (Sandbox Code Playgroud)

并在行动:

scala> val x = ?:("hel")(_ + "lo ")(_ * 2)(_ + "world")()
x: java.lang.String = hello hello world

scala> val x = ?:("hel")(_ + "lo ")(_ => (null: String))(_ + "world")()
x: java.lang.String = null
Run Code Online (Sandbox Code Playgroud)

  • 我已经等了7年才有人做出这个观察!谢谢. (10认同)