Skip to content

Instantly share code, notes, and snippets.

@scottashipp
Last active April 25, 2020 18:18
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 scottashipp/a2e76d98bb86ed054c0fb8317c2117ce to your computer and use it in GitHub Desktop.
Save scottashipp/a2e76d98bb86ed054c0fb8317c2117ce to your computer and use it in GitHub Desktop.
Null-safe operator for Scala?
// from https://code.scottshipp.com/2016/07/28/does-scala-have-the-safe-navigation-null-conditional-operator/
implicit class NullSafe[A, B](val a: A) extends AnyVal {
def ?(f: A => B): B = { if(a == null) null.asInstanceOf[B] else f(a) }
}
//example
val s = "Hello, World!"
s?(_.reverse)?(_.reverse) //returns "Hello, World!"
val sNull: String = null
sNull?(_.reverse)?(_.reverse) //returns null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment