-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathOptional.java
57 lines (46 loc) · 1.2 KB
/
Optional.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.NoSuchElementException;
public class Optional<T> {
private static final Optional<?> EMPTY = new Optional(Null.INSTANCE);
private T value;
protected Optional(T value){
this.value = value;
}
public static <T> Optional<T> of(T value){
return new Optional<T>(value);
}
@SuppressWarnings("unchecked")
public static <T> Optional<T> empty(){
return (Optional<T>) EMPTY;
}
public static <T> Optional<T> ofNullable(T value){
if(value == null){
return empty();
}else{
return of(value);
}
}
public boolean isPresent(){
return !(this.value == null || this == EMPTY);
}
public T get() throws NoSuchElementException {
if(isPresent()){
return value;
}else{
throw new NoSuchElementException();
}
}
public T orElse(T other) {
if(isPresent()){
return value;
}else{
return other;
}
}
private static class Null {
private static final Null INSTANCE = new Null();
private Null(){
// Private constructor
super();
}
}
}