Skip to content

Commit e7d9133

Browse files
committed
Simplified elvis-like operator
1 parent 215aed9 commit e7d9133

File tree

2 files changed

+100
-0
lines changed

2 files changed

+100
-0
lines changed

src/com/winterbe/java8/Take.java

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package com.winterbe.java8;
2+
3+
import java.util.Optional;
4+
import java.util.function.Function;
5+
6+
/**
7+
* Simplified elvis-like operator. You can achieve the same with Optional but Take has simpler syntax.
8+
*
9+
* @see Optional2
10+
* @author Benjamin Winterberg
11+
*/
12+
public class Take<T> {
13+
14+
private static final Take<?> EMPTY = new Take<>(null);
15+
16+
private T value;
17+
18+
private Take(T value) {
19+
this.value = value;
20+
}
21+
22+
public static <T> Take<T> of(T something) {
23+
return new Take<>(something);
24+
}
25+
26+
public <S> Take<S> take(Function<? super T, S> mapper) {
27+
if (!isPresent()) {
28+
return empty();
29+
}
30+
S result = mapper.apply(value);
31+
return new Take<>(result);
32+
}
33+
34+
public Optional<T> get() {
35+
return Optional.ofNullable(value);
36+
}
37+
38+
public T orElse(T fallback) {
39+
if (isPresent()) {
40+
return value;
41+
}
42+
return fallback;
43+
}
44+
45+
public boolean isPresent() {
46+
return value != null;
47+
}
48+
49+
@SuppressWarnings("unchecked")
50+
private static <T> Take<T> empty() {
51+
return (Take<T>) EMPTY;
52+
}
53+
54+
}

src/com/winterbe/java8/TakeTest.java

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
package com.winterbe.java8;
2+
3+
import java.util.Optional;
4+
5+
/**
6+
* @author Benjamin Winterberg
7+
*/
8+
public class TakeTest {
9+
10+
static class Outer {
11+
Nested nested = new Nested();
12+
13+
Nested getNested() {
14+
return nested;
15+
}
16+
}
17+
18+
static class Nested {
19+
Inner inner = new Inner();
20+
21+
Inner getInner() {
22+
return inner;
23+
}
24+
}
25+
26+
static class Inner {
27+
String foo = "foo";
28+
29+
String getFoo() {
30+
return foo;
31+
}
32+
}
33+
34+
public static void main(String[] args) {
35+
Outer something = new Outer();
36+
37+
Optional<String> optional = Take.of(something)
38+
.take(Outer::getNested)
39+
.take(Nested::getInner)
40+
.take(Inner::getFoo)
41+
.get();
42+
43+
System.out.println(optional.get());
44+
}
45+
46+
}

0 commit comments

Comments
 (0)