Stephan van Hulst wrote:Optional is not meant for method parameters.
Interesting, I haven't passed optional as a method parameter in my code yet. But, I wonder why one should not do that. Let's fork this into a separate thread if the answer is complicated so that OP is not affected.
It would be allowed to assign optionals from actuals, but not the other way around without operating on the optional first, such as using the null-coalescing operator:
Another method from Optional that could be made into a special operator is map(). An example using a combination of null-propagating and null-coalescing operators:
In plain Java, that would be:
Now, you REALLY never have to perform null-checks, because you simply use the actual type in your method parameters if you don't want to allow null.
If you have a reference type Foo, you would not be allowed to assign null to it. That also means that the compiler knows that you can assign a variable of type Foo to another variable of type Foo without problems, because a Foo can never be null. You're also allowed to assign a variable of type Foo to another variable of type Foo? . You're NOT allowed to assign a variable of type Foo? to a variable of type Foo, because you might be assigning null. All of this information is available at compile time. To be able to do that, you need to convince the compiler that you've got a backup plan when the value is null. That's what the null-coalescing operator is for.
Another way of looking at all of this is that the compiler will also snap at you if you try to do this:
The difference is that with the special syntax, the reverse IS allowed, and that the compiler automatically wraps the unwrapped object:
Stephan van Hulst wrote:It makes your API really unwieldy to use. Passing null into methods should be the exception rather than the norm, and you're forcing the client of your method to keep wrapping their arguments in a call to Optional.of(), just for the sake of making your method implementation more fun to write.
I agree over the wrapping point. While I see Optional as a good candidate for code that's present within the lines of a method, I am starting to realize that outside the scope of a method, it may not be a good thing to do.
Let me summarize for others reading this thread (Open to discussion):
Let me know if you the above list can be improved. +cows for you all !
Although you might end up with more lines of code, it simplifies the code and makes it more obvious what's going one, because you can name the two new methods accordingly.