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