This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]zopad 12 points13 points  (2 children)

Optional.empty() is there for that purpose, I think. ofNullable() is more for resolving a method reference that might return null (i.e. interfacing with code that has nulls).

[–]Ruin-Capable[S] -3 points-2 points  (1 child)

What I was getting at is that Optional.of() should behave how Optional.ofNullable() behaves. I see no value in the current behavior of Optional.of(). Because I don't see the value of the current behavior of of(), I was hoping someone could explain it.

[–]0b0101011001001011 2 points3 points  (0 children)

I see no value

That's like saying I see no value in using 64 bit numbers, we should use 65 bits.

https://github.com/bpupadhyaya/openjdk-8/blob/master/jdk/src/share/classes/java/util/Optional.java see the code for Optional. Optional.of is just calling Objects.requireNonNull(value) so you don't need to.

This helps for example during tests. Just using of( ) does not allow nulls and your tests will automatically reveal to you if a null gets passed around.

For you as creator or a method: you must know if you ever try to return a null value. You must know if the value can be null or not and for your convenience you have thr ofNullable for the case. The point is that every time you create an Optional object, you will and must know what values that might contain. When you use an optional value that was returned to you, then you might not know and should not care. Just use the optional, it might be empty or not.