Skip to content

Commit 0e03c6d

Browse files
committed
Add methods fromNullable(), or() and orNull() for the Optional class.
1 parent 1272dfe commit 0e03c6d

File tree

2 files changed

+40
-4
lines changed

2 files changed

+40
-4
lines changed

src/main/java/com/github/underscore/Optional.java

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.github.underscore;
22

33
public 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

src/test/java/com/github/underscore/UnderscoreTest.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
import static org.junit.Assert.assertEquals;
3131
import static org.junit.Assert.assertFalse;
3232
import 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

0 commit comments

Comments
 (0)