Uses for Optional

前端 未结 14 1616
眼角桃花
眼角桃花 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:13

    An Optional has similar semantics to an unmodifiable instance of the Iterator design pattern:

    • it might or might not refer to an object (as given by isPresent())
    • it can be dereferenced (using get()) if it does refer to an object
    • but it can not be advanced to the next position in the sequence (it has no next() method).

    Therefore consider returning or passing an Optional in contexts where you might previously have considered using a Java Iterator.

提交回复
热议问题