Last active
December 30, 2015 08:17
-
-
Save gpampara/6eba22fd6df277b89a09 to your computer and use it in GitHub Desktop.
Option?
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
// Normal null checking | |
Outer outer = new Outer(); | |
if (outer != null && outer.nested != null && outer.nested.inner != null) { | |
System.out.println(outer.nested.inner.foo); | |
} | |
// Safer | |
def resolve[A](x: A): Option[A] = Option(x) | |
Option(new Outer()).flatMap(x => resolve(x.nested)).flatMap(x => resolve(x.inner)).map(x => System.out.println(x)) | |
// Using syntax sugar | |
for { | |
a <- Option(new Outer()) | |
b <- resolve(a.nested) | |
c <- resolve(b.inner) | |
} yield System.out.println(c) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment