File tree Expand file tree Collapse file tree 2 files changed +28
-3
lines changed Expand file tree Collapse file tree 2 files changed +28
-3
lines changed Original file line number Diff line number Diff line change 2
2
3
3
import java .util .Optional ;
4
4
import java .util .function .Function ;
5
+ import java .util .function .Supplier ;
5
6
6
7
/**
7
8
* Simplified elvis-like operator. You can achieve the same with Optional but Take has simpler syntax.
@@ -19,15 +20,25 @@ private Take(T value) {
19
20
this .value = value ;
20
21
}
21
22
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
+
22
33
public static <T > Take <T > of (T something ) {
23
34
return new Take <>(something );
24
35
}
25
36
26
- public <S > Take <S > take (Function <? super T , S > mapper ) {
37
+ public <S > Take <S > take (Function <? super T , S > resolver ) {
27
38
if (!isPresent ()) {
28
39
return empty ();
29
40
}
30
- S result = mapper .apply (value );
41
+ S result = resolver .apply (value );
31
42
return new Take <>(result );
32
43
}
33
44
Original file line number Diff line number Diff line change @@ -40,7 +40,21 @@ public static void main(String[] args) {
40
40
.take (Inner ::getFoo )
41
41
.get ();
42
42
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
+
44
58
}
45
59
46
60
}
You can’t perform that action at this time.
0 commit comments