Uses for Optional

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

    Personally, I prefer to use IntelliJ's Code Inspection Tool to use @NotNull and @Nullable checks as these are largely compile time (can have some runtime checks) This has lower overhead in terms of code readability and runtime performance. It is not as rigorous as using Optional, however this lack of rigour should be backed by decent unit tests.

    public @Nullable Foo findFoo(@NotNull String id);
    
    public @NotNull Foo doSomething(@NotNull String id, @Nullable Bar barOptional);
    
    public class Book {
    
      private List pages;
      private @Nullable Index index;
    
    }
    
    List<@Nullable Foo> list = ..
    

    This works with Java 5 and no need to wrap and unwrap values. (or create wrapper objects)

提交回复
热议问题