by haspok · 3y ago · 0 comments
1. They are not composable (can't map or flatmap or fold/reduce them).
2. They can only represent one extra value, if you need more, you are back to square one (eg. you can't return an error value, only the fact that there is no value).
If we make another step, one could argue that even optionals are lacking, one should model the possible domain values with sums and products in such a way that no nulls or optionals are required. Do not try this in a language with such a basic type system as Java or even Kotlin though, you will run into the limits of the type system almost immediately.
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.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.
I never found the talk online, but here's the speaker deck: https://speakerdeck.com/mariofusco/monadic-java
1. They are not composable (can't map or flatmap or fold/reduce them).
Kotlin helpfully added mapNotNull() and similar methods. 2. you can't return an error value, only the fact that there is no value
Yes I much prefer Rust-like return values, the non-local control flow of exceptions leads to convoluted code and improper error handling.