Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement 'Maybe' in Java

Tags:

java

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?

like image 400
So8res Avatar asked Oct 16 '13 19:10

So8res


2 Answers

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).

like image 78
Mark Peters Avatar answered Oct 20 '22 17:10

Mark Peters


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.

like image 33
jhyry-gcpud Avatar answered Oct 20 '22 16:10

jhyry-gcpud