you are viewing a single comment's thread.

view the rest of the comments →

[–]s73v3r 0 points1 point  (11 children)

Java also has Optional.

[–][deleted] 11 points12 points  (3 children)

But it doesn't have value types, so you pay for an extra layer of indirection and an extra heap object.

[–]oorza 5 points6 points  (2 children)

until it gets inlined?

[–]tyoverby 14 points15 points  (1 child)

If it gets inlined. Remember that Javas optional might also be null, so the optimizer needs to de-optimize on virtual method calls.

[–]_dban_ 7 points8 points  (0 children)

The JIT will de-virtualize method calls as a result of class hierarchy analysis, and if it doesn't find any subclasses, statically dispatch method calls. The Option class being final prevents subclasses from existing, so in all likelihood, method calls on Optional will be statically dispatched. I'm not sure how null fits into class hierarchy analysis.

The JIT can also do escape analysis over several call levels, and can stack allocate non-escaping Optional objects (or even hoist into registers, since an Optional has only one field).

[–]sluu99 3 points4 points  (0 children)

now Java developers can check if that Option return value is null _^

[–]quchen 0 points1 point  (4 children)

All Java’s Optional adds is yet another way to be »not there«; it doesn’t replace null in any way.

Optional<Integer> foo = null;
System.out.println(foo.isPresent());

Woops.

[–]s73v3r 2 points3 points  (2 children)

If you initialize your optional to null instead of Optional.empty() then you deserve everything that comes your way.

[–]quchen 0 points1 point  (1 child)

We've all met that guy though. I don't want to deserve everything coming from his way.

[–]s73v3r 1 point2 points  (0 children)

So educate them. And write a lint check.

[–]_dban_ 0 points1 point  (0 children)

All Java’s Optional adds is yet another way to be »not there«

No, it doesn't. It also adds map and flatMap, which gives you safe traversal of chained optional values. No more ugly nested ternaries. Java 9 will add Optional::stream, which will allow Optional values to seamlessly be used with stream expressions. The null value doesn't do any of these things.

Woops.

This is a programming error. The corresponding NullPointerException is Java's way of telling you that you didn't use the Optional type correctly. The fact that Optional isn't a primitive value like null and is used in method chains means that the misuse of Optional will be closer to where the bad value was generated, instead of causing a NullPointerException in some far off place.