Best Scala imitation of Groovy's safe-dereference operator (?.)?

前端 未结 8 2023
心在旅途
心在旅途 2020-12-02 12:43

I would like to know what the best Scala imitation of Groovy\'s safe-dereference operator (?.), or at least some close alternatives are?

I\'ve discussed it breifly o

相关标签:
8条回答
  • 2020-12-02 13:20

    Monadic bind (flatMap/map) with the scala.Option type. Support is also provided by for-comprehensions. Scalaz provides an applicative functor style if you prefer.

    This is not equivalent, but a far better solution than Groovy's operator for many reasons.

    0 讨论(0)
  • 2020-12-02 13:20

    Not mine but a coworker's

    class NullCoalescer[T <: AnyRef](target: T) {
        def ?? (other: T) =
            if(target == null) other else target
    }
    object NullCoalescerConversions {
        implicit def toNullCoalescer[T <: AnyRef](target: T): NullCoalescer[T] = 
            new NullCoalescer(target)
    }
    
    println (System.getProperty("maybe") ?? "definitely")
    
    0 讨论(0)
提交回复
热议问题