The Option.map(Function) accepts a null as a return value from the Function#apply resulting in Some(null)

Issue #12 resolved
maurice@zeijen.net created an issue

The Option.map(Function) accepts a null as a return value from the Function#apply resulting in Some(null).

For example the following code results in Some(null):

Option<String> someOption = some("");
someOption.map(
    new Function<String, String>() {
        @Nullable @Override
        public String apply(@Nullable final String str) {
            return null;
        }
    }
);

I believe this should result in a NPE or Option.none().

Comments (2)

  1. Jed Wesley-Smith

    This is deliberate, and won't change. It in fact must happen to preserve the Functor laws so that composing two functions into one and mapping that is the same as mapping each function in succession.

    The behavior you want is provided by:

    Option<String> someOption = some("");
    someOption.flatMap(
      new Function<String, Option<String>>() {
        @Nullable @Override
        public Option<String> apply(@Nullable final String str) {
            return Option.none();
        }
      }
    );
    

    We could potentially provide a null aware alternative convenience for the above.

  2. Log in to comment