Last active
June 18, 2020 09:40
-
-
Save tonivade/1de9cd124ce195f3ebc13a695626d202 to your computer and use it in GitHub Desktop.
An example of Java 15 sealed classes, pattern matching instanceof and records
This file contains 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
import java.util.function.Function; | |
import java.util.function.Supplier; | |
public class Main { | |
public static void main(String args[]) { | |
var some = new Some<>("hello"); | |
var result = some.map(String::toUpperCase); | |
System.out.println(result.orElse("")); | |
} | |
} | |
sealed interface Option<T> permits Some, None { | |
default <R> Option<R> map(Function<T, R> mapper) { | |
return fold(None::new, mapper.andThen(Some::new)); | |
} | |
default T orElse(T value) { | |
return fold(() -> value, Function.identity()); | |
} | |
default <R> R fold(Supplier<R> noneCase, Function<T, R> someCase) { | |
if (this instanceof Some<T> some) { | |
return someCase.apply(some.value()); | |
} else { | |
return noneCase.get(); | |
} | |
} | |
} | |
record Some<T>(T value) implements Option<T> {} | |
record None<T>() implements Option<T> {} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment