Skip to content

Instantly share code, notes, and snippets.

@fcracker79
Last active December 14, 2022 07:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fcracker79/ec283cdb9a57d2d4b9f771a5d268f19e to your computer and use it in GitHub Desktop.
Save fcracker79/ec283cdb9a57d2d4b9f771a5d268f19e to your computer and use it in GitHub Desktop.
Optional and switch
public class TestOptional {
private sealed interface MyOptional<T> {
MyOptional<?> EMPTY = new MyEmpty<>();
boolean hasValue();
T get();
static <T> MyOptional<T> of(T t) {
return new MyJust<>(t);
}
static <T> MyOptional<T> empty() {
return (MyOptional<T>) EMPTY;
}
}
private static final class MyJust<T> implements MyOptional<T> {
private final T t;
private MyJust(T t) {
this.t = t;
}
public boolean hasValue() {
return true;
}
public T get() {
return this.t;
}
}
private static final class MyEmpty<T> implements MyOptional<T> {
public boolean hasValue() {
return false;
}
public T get() {
throw new IllegalArgumentException();
}
}
public static void main(String ... args) {
var optionalValue = MyOptional.of("hello");
var value = switch (optionalValue) {
case MyJust<String> j -> j.get();
case MyEmpty<String> w -> "nothing";
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment