0

I am trying to understand reasons behind different Option/Optional semantics in probably 3 most used implementations in Java ecosystem: Java 8, Functional Java and Guava.

Considering following three snippets.

  1. java.util.Optional.of(100).map(i -> null) results in Optional.empty.
  2. fj.data.Option.some(100).map(i -> null) results in Some(null).
  3. com.google.common.base.Optional.of(100).transform(i -> null) results NullPointerException.

What are the reasons behind 3 choices? If appicable, what can be considered most "pure" or "correct" from functional programming point of view? For example, in terms of viewing Option type as monad, what would be most correct; or what can be considered most composable? It would also interesting to know how this is handled in functional languages that allow nulls.

hgrey
  • 3,033
  • 17
  • 21
  • Different Objective of coding(optimise, secure or without crash) I think, you should read for example Java good practice book. For example avoid null when return list, you should return emptyList. Exception should remain as their name, Exceptions. – Destrif Jun 23 '16 at 09:49
  • The same reason why C# and Java aren't exactly equal. Different developers with different opinions how "it" should work. Asking _us_ why _they_ thought so is quite strange. – Tom Jun 23 '16 at 09:51
  • 1
    @Tom slightly expanded the question to be more specific – hgrey Jun 23 '16 at 10:07

1 Answers1

1

I dont see a real reason for Guava's behavior. As for the other two, it depends how the author defined null values:

  • java 8 defined null value to be the absence of value, thus you get an Optional.empty
  • functional java seemed to have defined null as a possible value, distinct from no value.

    For a more concrete reason, lets take a look at map definition:

    public final <B> Option<B> map(final F<A, B> f) {
       return isSome() ? some(f.f(some())) : Option.none();
    }
    

    As long as the 'container' is not None, its transformed value will not be None. To get a result similar to java 8, fromNull could be used.

As for 'pure' or 'correct', probably a similar answer to the old is 0 a natural number? :)

Community
  • 1
  • 1
Shlomi
  • 4,708
  • 1
  • 23
  • 32