Should Optional.ofNullable() be used for null check?

后端 未结 3 766
一向
一向 2020-12-19 04:33

Which null-check is preferable?

Optional.ofNullable(port).ifPresent(settings::setPort);

or

if (port != null) {
   settings.         


        
3条回答
  •  生来不讨喜
    2020-12-19 05:23

    It is dependent on several factors when to use this. If port is a property within the class, probably using Optional is a bit overkill. (and don't useOptionals as property as they are not serializbie)

    I think Optionals are great when for example writing a library.

    public Optional getPort()
    

    Is much more descriptive for other developers then

    // Returns null if not set
    public Integer getPort()
    

提交回复
热议问题