Why should Java 8's Optional not be used in arguments

前端 未结 20 1626
我寻月下人不归
我寻月下人不归 2020-11-22 11:33

I\'ve read on many Web sites Optional should be used as a return type only, and not used in method arguments. I\'m struggling to find a logical reason why. For example I h

20条回答
  •  无人及你
    2020-11-22 12:36

    One more approach, what you can do is

    // get your optionals first
    Optional p1 = otherObject.getP1();
    Optional p2 = otherObject.getP2();
    
    // bind values to a function
    Supplier calculatedValueSupplier = () -> { // your logic here using both optional as state}
    

    Once you have built a function(supplier in this case) you will be able to pass this around as any other variable and would be able to call it using

    calculatedValueSupplier.apply();
    

    The idea here being whether you have got optional value or not will be internal detail of your function and will not be in parameter. Thinking functions when thinking about optional as parameter is actually very useful technique that I have found.

    As to your question whether you should actually do it or not is based on your preference, but as others said it makes your API ugly to say the least.

提交回复
热议问题