Skip to content

Instantly share code, notes, and snippets.

@lerno
Last active August 29, 2015 14:15
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 lerno/6d820600fbf30797ccf4 to your computer and use it in GitHub Desktop.
Save lerno/6d820600fbf30797ccf4 to your computer and use it in GitHub Desktop.
Implicit unwrap vs optionals - trivial example to illustrate implicit conversion from "possibly null" to "not null" with annotations.
// Assume we also have the following:
void doSomethingWithFoo(@NotNull foo) { ... }
void doSomethingNull() { ... }
void doSomethingMore() { ... }
void doSomething(@Nullable Foo foo)
{
// doSomethingWithFoo(foo); <- this would have been an error in the IDE
// Since foo is @Nullable at this point
if (foo == null)
{
doSomethingNull();
return;
}
// Foo is null checked, consequently in all the following
// The IDE assumes foo is not null, i.e. as if foo is @NotNull
doSomethingWithFoo(foo);
if (foo.bar() == true)
{
doSomethingMore();
}
}
// With optional
void doSomething(Optional<Foo> foo)
{
if (!foo.isPresent())
{
doSomethingNull();
return;
}
doSomethingWithFoo(foo.get());
if (foo.get().bar() == true)
{
doSomethingMore();
}
}
// With optional #2
void doSomething(Optional<Foo> optionalFoo)
{
if (!optionalFoo.isPresent())
{
doSomethingNull();
return;
}
Foo foo = optionalFoo.get();
doSomethingWithFoo(foo);
if (foo.bar() == true)
{
doSomethingMore();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment