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

前端 未结 8 2052
心在旅途
心在旅途 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

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

提交回复
热议问题