The Optional Class – Streams

16.6 The Optional Class

When a method returns a null value, it is not always clear whether the null value represents a valid value or the absence of a value. Methods that can return null values invariably force their callers to check the returned value explicitly in order to avoid a NullPointerException before using the returned value. For example, method chaining, which we have seen for composing stream pipelines, becomes cumbersome if each method call must be checked to see whether it returns a null value before calling the next method, resulting in a cascade of conditional statements.

The concept of an Optional object allows the absence of a value to be handled in a systematic way, making the code robust by enforcing that a consumer of an Optional must also deal with the case when the value is absent. Taking full advantage of Optional wrappers requires using them the right way, primarily to handle situations where the value returned by a method is absent.

The generic class Optional<T> provides a wrapper that represents either the presence or absence of a non-null value of type T. In other words, the wrapper either contains a non-null value of type T or no value at all.

Example 16.8 illustrates using objects of the Optional<T> class.

Declaring and Returning an Optional

Example 16.8 illustrates declaring and returning an Optional. A book is represented by the Book class that has an optional blurb of type String; that is, a book may or may not have a blurb. The Optional<T> class is parameterized with the type String in the declaration, and so is the return type of the method that returns the optional blurb.

Click here to view code image

class Book {
  private Optional<String> optBlurb;
  public Optional<String> getOptBlurb() { return optBlurb; }
  //…
}

Leave a Reply

Your email address will not be published. Required fields are marked *