Optional != @Nullable
Sam Pullara
sam at sampullara.com
Sun Sep 30 16:20:05 PDT 2012
On Sun, Sep 30, 2012 at 4:09 PM, Jed Wesley-Smith <jed.wesleysmith at gmail.com
> wrote:
> 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.
>
I think there is more to the cost than just the allocation. I'm sure Brian
could chime in with further performance issues. I was under the impression
that it affected things like escape analysis and other optimizations.
> 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.
>
In the context of this discussion, it was proposed that that you could have
an Optional<T> that contained a null value. Which breaks a bunch of the
value of Optional if you ask me. In Scala I do see far more NPEs around
initialization order :)
> 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.
>
We can quite easily change this so that it works at compile time rather
than introduce Optional. What I meant was, they could be treated in the
same way as Optional if it were a priority.
Sam
More information about the lambda-dev
mailing list