Optional

작성자 김성민

개요

Java 언어 설계자인 Brian Goetz는 Optional을 만든 의도를 다음과 같이

공식 API 문서

📢

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. 메소드가 반환할 결과 값이 '없음'을 명백하게 표현할 필요가 있고, null을 반환하면 에러가 발생할 가능성이 높은 상황에서 메소드의 반환 타입으로 Optional을 사용하자는 것이 Optional을 만든 주된 목적이다. Optional 타입의 변수의 값은 절대 null이어서는 안 되며, 항상 Optional 인스턴스를 가리켜야 한다.

Optional 이란?

Java 8부터 추가된 null이 올 수 있는 값을 감싸는 Wrapper 클래스로,

NPE(NullPointerException)

Optional 올바르게 사용하기