Uses for Optional

前端 未结 14 1433
眼角桃花
眼角桃花 2020-11-22 01:01

Having been using Java 8 now for 6+ months or so, I\'m pretty happy with the new API changes. One area I\'m still not confident in is when to use Optional. I se

14条回答
  •  时光说笑
    2020-11-22 01:18

    Optional class lets you avoid to use null and provide a better alternative:

    • This encourages the developer to make checks for presence in order to avoid uncaught NullPointerException's.

    • API becomes better documented because it's possible to see, where to expect the values which can be absent.

    Optional provides convenient API for further work with the object: isPresent(); get(); orElse(); orElseGet(); orElseThrow(); map(); filter(); flatmap().

    In addition, many frameworks actively use this data type and return it from their API.

提交回复
热议问题