Guava's Optional class comes dangerously close to being a useful Maybe
type in Java. All I want to do is extend it a bit:
class Maybe<X> extends Optional<X> {
public Maybe<Y> map(Function<X, Y> f) {
if (isPresent()) {
return Maybe.of(f.apply(get()));
}
return Maybe.absent();
}
}
Is that so hard? Apparently yes, it is. Java has no idea what the Y
type is in the map
function, and everything dies horribly. Is it possible to write a generic map
in Java?
You're looking for Optional.transform(Function)
, following Guava's convention of calling all map
-style functions "transform" (e.g. Lists.transform, Iterables.transform, etc).
This is, as of JDK8, implemented as java.util.Optional, and it seems to have the mapping function that you're looking for as it integrates with Streams. Here is the documentation.
I know this reply is quite late, but I'm adding it as an answer for the benefit of others searching for this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With