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

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

    Create this implicit conversion.

    class SafeDereference[A](obj: A) {
      def ?[B >: Null](function: A => B): B = if (obj == null) null else function(obj)
    }
    
    implicit def safeDereference[A](obj: A) = new SafeDereference(obj)
    

    The usage isn't as pretty as Groovy, but it's not awful.

    case class Address(state: String)
    case class Person(first: String, last: String, address: Address)
    val me = Person("Craig", "Motlin", null)
    
    scala> me ? (_.first)
    res1: String = Craig
    
    scala> me ? (_.address)
    res2: Address = null
    
    scala> me ? (_.address) ? (_.state)
    res3: String = null
    

提交回复
热议问题