How to write a proper null-safe coalescing operator in scala?

前端 未结 1 1285
野的像风
野的像风 2020-12-01 03:45

Having seen the answers coming out of questions like this one involving horror shows like trying to catch the NPE and dredge the mangled name out of the stack trace, I am as

相关标签:
1条回答
  • 2020-12-01 04:28

    Like so:

    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))
    }
    

    And in action:

    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
    
    0 讨论(0)
提交回复
热议问题