Skip to content

Commit 76ff6b6

Browse files
committed
More null safe operations
1 parent e7d9133 commit 76ff6b6

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

src/com/winterbe/java8/Take.java

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import java.util.Optional;
44
import java.util.function.Function;
5+
import java.util.function.Supplier;
56

67
/**
78
* Simplified elvis-like operator. You can achieve the same with Optional but Take has simpler syntax.
@@ -19,15 +20,25 @@ private Take(T value) {
1920
this.value = value;
2021
}
2122

23+
public static <T> Optional<T> of(Supplier<T> resolver) {
24+
try {
25+
T result = resolver.get();
26+
return Optional.ofNullable(result);
27+
}
28+
catch (NullPointerException e) {
29+
return Optional.empty();
30+
}
31+
}
32+
2233
public static <T> Take<T> of(T something) {
2334
return new Take<>(something);
2435
}
2536

26-
public <S> Take<S> take(Function<? super T, S> mapper) {
37+
public <S> Take<S> take(Function<? super T, S> resolver) {
2738
if (!isPresent()) {
2839
return empty();
2940
}
30-
S result = mapper.apply(value);
41+
S result = resolver.apply(value);
3142
return new Take<>(result);
3243
}
3344

src/com/winterbe/java8/TakeTest.java

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,21 @@ public static void main(String[] args) {
4040
.take(Inner::getFoo)
4141
.get();
4242

43-
System.out.println(optional.get());
43+
System.out.println(optional.isPresent());
44+
45+
something.getNested().inner = null;
46+
Optional<String> optional2 = Take.of(() ->
47+
something.getNested().getInner().getFoo());
48+
System.out.println(optional2.isPresent());
49+
50+
51+
String x = null;
52+
String y = "boo";
53+
String z = Take.of(x).orElse(y);
54+
55+
System.out.println(z);
56+
57+
4458
}
4559

4660
}

0 commit comments

Comments
 (0)