Last active
April 25, 2020 18:18
-
-
Save scottashipp/a2e76d98bb86ed054c0fb8317c2117ce to your computer and use it in GitHub Desktop.
Null-safe operator for Scala?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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