3 ms·
In modern Java you could do this: sealed interface Option<T> permits Some<T>, None<?> {} record Some<T>(T value) implements Option<T> {} record None() im
by kaba0 4y ago
In modern Java you could do this:
sealed interface Option<T> permits Some<T>, None<?> {}
record Some<T>(T value) implements Option<T> {}
record None() implements Option<T> {
static <T> None<T> none() { return new None<>(); // can also be a single instance
}
}
The only less than ideal part is that None needs the generic type, but that can be easily circumvented by adding a generic helper method. You can add all the Monad goodies to the Option interface and you will even get exhaustive switch cases with pattern matching. The only thing Java’s type system can’t express is abstracting those Monad goodies, but it can absolutely implement them on a case-by-case basis.
- sn9 4y agoMario Fusco gave a talk showing how to implement monadic patterns in Java years ago. I never found the talk online, but here's the speaker deck: https://speakerdeck.com/mariofusco/monadic-java https://speakerdeck.com/mariofusco/monadic-java
- haspok 4y agoThank you for bringing this to my attention, my current project is on Java 11, and I'm really struggling with the restrictions around enums (the poor man's sum type :)) and interfaces... maybe I can push for Java 17 at least! The fundamental problem in Java is, however, what you stated in your last sentence: you are limited in abstraction, in most cases you have to implement the specifics.