예를 들어, 앞 절의 안전한 inverse 메서드를 고려해보자. 여기에 안전한 루트 메서드도 있다고 하자.
public static Optional<Double> squareRoot(Double x) {
return x < 0 ? Optional.empty() : Optional.of(Math.sqrt(x));
}
이제 다음과 같이 역수의 루트를 계산할 수 있다.
Optional<Double> result = inverse(x).flatMap(Test::squareRoot);
원한다면 다음과 같이 할 수도 있다.
Optional<Double> result = Optional.of(-4.0)
.flatMap(Test::inverse).flatMap(Test::squareRoot);
inverse나 squareRoot 메서드 중 하나가 Optional.empty()를 리턴하면 결과는 비어 있게 된다.
<Note>
Stream 인터페이스(44페이지에 있는 “2.3 filter, map, flatMap 메서드” 절 참고)에서 이미 flatMap 메서드를 살펴봤다. 이때는 스트림을 돌려주는 두 메서드를 합성해 결과로 나오는 스트림들의 스트림을 펼쳐내는 데 flatMap 메서드를 사용했다. 옵션 값을 크기가 0 또는 1인 스트림으로 생각하면 Optional.flatMap 메서드도 같은 방식으로 동작한다.