Last active
December 14, 2022 07:32
-
-
Save fcracker79/ec283cdb9a57d2d4b9f771a5d268f19e to your computer and use it in GitHub Desktop.
Optional and switch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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