Optional != @Nullable

Jed Wesley-Smith jed.wesleysmith at gmail.com
Sun Sep 30 16:09:41 PDT 2012

On 1 October 2012 08:44, Sam Pullara <sam at sampullara.com> wrote:

> If that is what you think it is, then I am definitely against it.
> Introducing a runtime cost for documentation seems like a bad idea to me.

I believe this runtime cost (a single allocation) may be significantly
over-stated. The JVM is already heavily optimised for small short-lived
object creation, and there would be obvious scope for further HotSpot
optimisation of these (such as stack-allocation or even elision in hot
loops) if they become common. NPEs are much more expensive to raise.

It is also definitely not documentation, it is type safety.

> Especially since we aren't planning on changing the entire JDK library to
> return Optional<T> when they may return null.

Of course not, that isn't an option [ok, lame pun intended]. However, it is
easy to bring a nullable thing into an Option if needed. This has been the
general experience in Scala where the code that interfaces with legacy Java
has judicious wrapping into Option and NPEs are mostly a thing of the past.

> At this point in Java's life I am willing to concede that null exists and
> having a better way of dealing with it is great but it should deal with it
> in the context of current libraries. The transitivity,  will stop as soon
> as you encounter an API that doesn't support Optional as you'll need to be
> explicit.

Right, so explicitly dealing with existing nulls is as easy as:

public static <T> Option<T> option(@Nullable T t) {
  if (t == null)
    return none();
  return some(t);

Don't @Nullable/@NotNull have similar transitivity?

No they don't. You need an external static analysis tool to give you that –
as I showed before the compiler doesn't know or care and if you change
them, the changes don't carry through to the caller.

More information about the lambda-dev mailing list