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

前端 未结 20 1640
我寻月下人不归
我寻月下人不归 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<String> p1 = otherObject.getP1();
    Optional<BigInteger> p2 = otherObject.getP2();
    
    // bind values to a function
    Supplier<Integer> 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.

    0 讨论(0)
  • 2020-11-22 12:37

    Optionals aren't designed for this purpose, as explained nicely by Brian Goetz.

    You can always use @Nullable to denote that a method argument can be null. Using an optional does not really enable you to write your method logic more neatly.

    0 讨论(0)
提交回复
热议问题