JAVA
Optional<T>
고민말고생각하는사람
2024. 2. 23. 11:52
강의 학습 중, Optional 이 자주 사용되고 있어 알아보고자 한다.
java.util public final class Optional<T> A container object which may or may not contain a non-null value. If a value is present, isPresent() returns true. If no value is present, the object is considered empty and isPresent() returns false. Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (returns a default value if no value is present) and ifPresent() (performs an action if a value is present). This is a value-based class; programmers should treat instances that are equal as interchangeable and should not use instances for synchronization, or unpredictable behavior may occur. For example, in a future release, synchronization may fail.
API Note: Optional is primarily intended for use as a method return type where there is a clear need to represent "no result," and where using null is likely to cause errors. A variable whose type is Optional should never itself be null; it should always point to an Optional instance. Since: 1.8
란다.
Optinal이란?
컨테이너다. null값이거나 null값이 아닌 Obejct를 담을 수 있는 컨테이너다.
만약 값이 들어있다면, isPresent() 메서드로 진위를 파악할 수 있다.
값이 있다면 true, 비어 있다면 false.
get() 메서드를 통해 Optional<T> 에 담긴 Obejct를 가져올 수 있으나, 바람직하지는 않다.
null 이 반환될 수 있으며, null 로 인해 수 많은 오류를 접하게 될 수 있기 때문이다.
이러한 단점을 보완하기 위해,
Optional<T>은 ifPresent() 메서드를 통해 값이 있거나 없을 때에 액션을 취하도록 지원 해준다.
public void ifPresent(Consumer<? super T> action) {
if (value != null) {
action.accept(value);
}
}
예제에서는 아래와 같은 코드를 작성했다.
// 결과값이 있으면 예외 발생 시키기.
result.ifPresent(m -> {
throw new IllegalStateException("이미 존재하는 회원");
});
또는, orElseThrow() 등과 같은 메서드도 제공한다고 한다.
(필요해지면 알아보자.)
요약
Optional 은
- 언제든 문제를 야기할 수 있는 null 과 관련된 약점을 보완할 수 있도록 도와주는 클래스이다.
- 기능성 포장지라고 생각하면 편하다.
- 포장된 객체를 get()을 통해 바로 꺼낼 수도 있다.
- 그 외에도 다양하게 활용 가능하다.