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

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

    The pattern with Optional is for one to avoid returning null. It's still perfectly possible to pass in null to a method.

    While these aren't really official yet, you can use JSR-308 style annotations to indicate whether or not you accept null values into the function. Note that you'd have to have the right tooling to actually identify it, and it'd provide more of a static check than an enforceable runtime policy, but it would help.

    public int calculateSomething(@NotNull final String p1, @NotNull final String p2) {}
    

提交回复
热议问题