Skip to content

Optional 소개

Jeonghyun Kang edited this page May 23, 2022 · 3 revisions

Optional로 감싸기

이전의 방식

그냥 Null을 반환하고 클라이언트 코드에서 체크

public Progress getProgress() {
    return progress;
}

Progress progress = spring_boot.getProgress();
if (progress != null) {
    System.out.println("Not null");
}

Null일 경우 예외처리

public Progress getProgress() {
    if (this.progress == null) {
        throw new IllegalStateException();
    }
    return progress;
}

Optional 사용

public Optional<Progress> getProgress() {
    return Optional.ofNullable(progress);
}

Optional<Progress> progress = spring_boot.getProgress();
if (progress.isPresent()) {
    System.out.println("Not null");
}

주의할 것

Primitive type

primitive type용 Optional이 따로 있다. (성능이 더 좋음)

Optional.of(10);    // (X)
OptionalInt.of(10); // (O)

비어있는 Optional 반환

  • 절대 null을 return하면 안된다.
public Optional<T> getItem() {
    return null
  • Optional.empty()를 return 한다.
public Optional<T> getItem() {
    return Optional.empty();

아래 클래스는 Optional로 감싸지 않는다.

그 자체로 비어있는지 아닌지 확인이 가능하다.

  • Collection
  • Map
  • Stream Array
  • Optional
Clone this wiki locally