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

前端 未结 20 1909
我寻月下人不归
我寻月下人不归 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:20

    This advice is a variant of the "be as unspecific as possible regarding inputs and as specific as possible regarding outputs" rule of thumb.

    Usually if you have a method that takes a plain non-null value, you can map it over the Optional, so the plain version is strictly more unspecific regarding inputs. However there are a bunch of possible reasons why you would want to require an Optional argument nonetheless:

    • you want your function to be used in conjunction with another API that returns an Optional
    • Your function should return something other than an empty Optional if the given value is empty
    • You think Optional is so awesome that whoever uses your API should be required to learn about it ;-)

提交回复
热议问题