File tree Expand file tree Collapse file tree 2 files changed +40
-4
lines changed
main/java/com/github/underscore
test/java/com/github/underscore Expand file tree Collapse file tree 2 files changed +40
-4
lines changed Original file line number Diff line number Diff line change 11package com .github .underscore ;
22
33public final class Optional <T > {
4+ private static final Optional <?> EMPTY = new Optional ();
45 private final T arg ;
56 private final boolean absent ;
67
@@ -9,20 +10,43 @@ private Optional() {
910 this .absent = true ;
1011 }
1112
12- private Optional (T arg ) {
13+ private Optional (final T arg ) {
1314 this .arg = arg ;
1415 this .absent = false ;
1516 }
1617
17- public static <T > Optional <T > of (T arg ) {
18+ public static <T > Optional <T > of (final T arg ) {
1819 return new Optional <T >(arg );
1920 }
2021
21- public static <T > Optional <T > absent () {
22- return new Optional <T >();
22+ public static <T > Optional <T > fromNullable (final T nullableReference ) {
23+ return nullableReference == null ? Optional .<T >absent ()
24+ : new Optional <T >(nullableReference );
25+ }
26+
27+ @ SuppressWarnings ("unchecked" )
28+ public static <T > Optional <T > absent () {
29+ return (Optional <T >) EMPTY ;
2330 }
2431
2532 public T get () {
33+ if (absent ) {
34+ throw new IllegalStateException ("Optional.get() cannot be called on an absent value" );
35+ }
36+ return arg ;
37+ }
38+
39+ public T or (final T defaultValue ) {
40+ if (absent ) {
41+ return defaultValue ;
42+ }
43+ return arg ;
44+ }
45+
46+ public T orNull () {
47+ if (absent ) {
48+ return null ;
49+ }
2650 return arg ;
2751 }
2852
Original file line number Diff line number Diff line change 3030import static org .junit .Assert .assertEquals ;
3131import static org .junit .Assert .assertFalse ;
3232import static org .junit .Assert .assertTrue ;
33+ import static org .junit .Assert .fail ;
3334
3435/**
3536 * Underscore library unit test.
@@ -232,6 +233,17 @@ public void optional() {
232233 assertEquals (Optional .of ("123" ).hashCode (), Optional .of ("123" ).hashCode ());
233234 assertEquals ("Optional.absent()" , Optional .absent ().toString ());
234235 assertEquals ("Optional.of(1)" , Optional .of (1 ).toString ());
236+ assertEquals ("Optional.absent()" , Optional .fromNullable (null ).toString ());
237+ assertEquals ("Optional.of(1)" , Optional .fromNullable (1 ).toString ());
238+ assertEquals ("1" , Optional .absent ().or (1 ).toString ());
239+ assertEquals ("1" , Optional .of (1 ).or (2 ).toString ());
240+ assertEquals (null , Optional .absent ().orNull ());
241+ assertEquals ("1" , Optional .of (1 ).orNull ().toString ());
242+ try {
243+ Optional .absent ().get ();
244+ fail ("IllegalStateException expected" );
245+ } catch (IllegalStateException ex ) {
246+ }
235247 }
236248
237249 @ Test
You can’t perform that action at this time.
0 commit comments