Skip to content

Instantly share code, notes, and snippets.

@frohoff
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frohoff/6f96e55c88d007223511 to your computer and use it in GitHub Desktop.
Save frohoff/6f96e55c88d007223511 to your computer and use it in GitHub Desktop.
object NullSafeConversions {
implicit def ns[A](a:A) = new NullSafe(a)
implicit def ro[A](o:Option[A]) = new RichOption(o)
def ?[A](a:A) = if (a == null) Some(a) else None
case class NullSafe[A](a:A) extends AnyVal {
def ?[B >: Null](f: A => B):B = if (a != null) f(a) else null
}
case class RichOption[A](o:Option[A]) extends AnyVal {
def ?[B](f: A => B):Option[B] = { o.map(f) }
}
}
object Test extends App {
import NullSafeConversions._
import scala.collection.immutable._
case class X(y:Y, z:Z)
case class Y(x:X, z:Z)
case class Z(x:X, y:Y)
val x:X = X(null,null)
val z:Z
= try { x.y.z } catch { case _:Throwable => null }
val nz:Z
= x?(_.y)?(_.z)
val oz:Option[Z]
= ?(x)?(_.y)?(_.z)
val list1:List[List[List[String]]]
= List(List(List("1")))
val l1:String
= list1(0)(0)(0)
val ol1:String
= list1?(_(0))?(_(0))?(_(0))
val nl1:Option[String]
= ?(list1)?(_(0))?(_(0))?(_(0))
val list2:List[List[Int]]
= List(List(1))
val l2:Int
= list2(0)(0)
val nl2:Any
= list2?(_(0))?(_(0)) // expected
val ol2:Option[Int]
= ?(list2)?(_(0))?(_(0))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment