Skip to content
Advertisement

Difference between Java Optional and Scala Option

At the very end, this article introducing to new Java 8 Optional, states that

Optional is not nearly as powerful as Option[T] in Scala (but at least it doesn’t allow wrapping null). The API is not as straightforward as null-handling and probably much slower. But the benefit of compile-time checking plus readability and documentation value of Optional used consistently greatly outperforms disadvantages

I have a very basic knowledge of Scala and I’m getting familiar with Java 8 Optional, so at a first sight, it’s not clear to me what are the differences between the two, if any.

I know, for example, that in Scala I can use pattern matching to test Option and make my life easier. But, excluding what are the features of Scala’s syntax, I would like to know if there’s something I can do with Option in Scala that I cannot do with Optional in Java.

Hope this is not marked as silly question, but every time I read that ‘powerful’, question marks fly over my head.

Advertisement

Answer

If we’re talking about differences that aren’t syntax-related, Tomasz Nurkiewicz pretty much highlights the biggest one in the opening paragraphs of his blog post:

Optional was introduced in Java 8 so obviously it is not used throughout the standard Java library – and never will be for the backward compatibility reasons.

(emph. mine – although I wouldn’t be so adamant on “never”, given the new default methods)

So the biggest difference, and the greatest advantage of Scala’s Option, seems to be simply that it’s much more tightly integrated into the language’s API.

First of all, you’re very likely to obtain exposure to it, and hence its usage pattern, early on when you start using Scala – most notably, through Scala’s Map#get.

And inversely – if you look at Scala’s Option API, you will see that it is “spliced” into Scala’s collection hierarchy, meaning that you can transparently use it as a collection whenever you need so – e.g. without, say, the end developer of your library ever dealing with its particularities.

Advertisement