Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the key differences between Java 8's Optional, Scala's Option and Haskell's Maybe?

I've read a few posts on Java 8's upcoming Optional type, and I'm trying to understand why people keep suggesting it's not as powerful as Scala's Option. As far as I can tell it has:

  • Higher order functions like map and filter using Java 8 lambdas.
  • Monadic flatMap
  • Short circuiting through getOrElse type functions.

What am I missing?

like image 741
Dominic Bou-Samra Avatar asked Mar 13 '14 04:03

Dominic Bou-Samra


2 Answers

Some possibilities come to mind (OTOH, I haven't seen people actually saying that, so they might mean something else):

  1. No pattern matching.

  2. No equivalent to Scala's fold or Haskell's fromMaybe: you have to do optional.map(...).orElseGet(...) instead.

  3. No monadic syntax.

I also wouldn't call any of these "less powerful" myself, since you can express everything you can with the corresponding Scala/Haskell types; these are all conciseness/usability concerns.

like image 141
Alexey Romanov Avatar answered Nov 07 '22 19:11

Alexey Romanov


Optional and Maybe are effectively in correspondence. Scala has None and Some[A] as subclassing Option[A] which might be more directly comparable to Java since Java could have done the same.

Most other differences either have to do with the ease of handling Maybe/Option in Haskell/Scala which won't translate since Java is less expressive as a language or the consistency of use of Maybe/Option in Haskell/Scala where many of the guarantees and conveniences afforded by the type only kick in once most libraries have agreed to use optional types instead of nulls or exceptions.

like image 39
J. Abrahamson Avatar answered Nov 07 '22 20:11

J. Abrahamson