Optional, Guava and Java 8

Edouard Kaiser
Mar 7, 2018 · 6 min read
public abstract class Optional<T> implements Serializable { 
public abstract boolean isPresent();
public abstract T get();
public abstract T or(T defaultValue);
....
}
final class Absent extends Optional<Object> { .... } 
final class Present<T> extends Optional<T> { .... }
public static <T> Optional<T> of(T value) { 
return new Present<T>(checkNotNull(value));
}
public static <T> Optional<T> fromNullable(@Nullable T value) { return (value == null) ? Optional<T>.absent() : new Present<T>(value);
}
@Override 
public boolean isPresent() {
return false;
}
@Override
public Object get() {
throw new IllegalStateException("value is absent");
}
public boolean isPresent() { 
return value != null;
}
@Override 
public boolean isPresent() {
return true;
}
@Override
public T get() {
return value;
}
@Override 
public int hashCode() {
return 0x598df91c + value.hashCode();
}
public static <T> Optional<T> of(T value) { 
return new Optional<>(value);
}
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
public boolean isPresent() { 
return value != null;
}
public T get() {
if (value == null) {
throw new NoSuchElementException("No value present");
}
return value;
}
public Optional<T> filter(Predicate<? super T> predicate) public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper)
@Override 
public int hashCode() {
return Objects.hashCode(value);
}
@Nullable private final String flightNumber; public Optional<String> getFlightNumber() { 
return Optional.ofNullable(this.flightNumber)
}

Edouard Kaiser

Written by

Engineering Manager @Atlassian, technology lover, Java engineer originally, distributed systems aficionado and team builder.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade