Last active
August 29, 2015 14:15
-
-
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.
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
// 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