Skip to content

Instantly share code, notes, and snippets.

@gpampara
Last active December 30, 2015 08:17
Show Gist options
  • Save gpampara/6eba22fd6df277b89a09 to your computer and use it in GitHub Desktop.
Save gpampara/6eba22fd6df277b89a09 to your computer and use it in GitHub Desktop.
Option?
// 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