Optionalは「値」があるかもしれないし、ないかもしれない」と伝えるためのクラスspring Data JPAの戻り値は勝手にOptionalの型になってるからfindbyidとかfindallの戻り値の時はメソッドの部分だけ書けばいい。一般的には以下のようにオブジェクトを定義する。Optionalのメソッドを使うときは必ずOptionalインポート文が必要。
import java.util.Optional;
Optional<T> オブジェクト名 = Optional.ofNullable(nullの可能性があるオブジェクト名);
of
中身の入ったOptionalを作る
例)Optional<String> strOptional = Optional.of("Hello");
これで "Hello" が中身にあるOptionalクラスのインスタンスができる。
ofメソッドは引数に null を指定すると「中身がない!」となり NullPointerException が出るから使い勝手よくない。
確実に中身が入っているとわかっている Optional ではあまり意味がないので次の ofNullable のほうが使い勝手が良い。
ofNullable
中身が null かもしれない Optional を作る
例1ullじゃない)String str = "Hello";
Optional<String> strOptional = Optional.ofNullable(str);
例2null)String strNull = null;
Optional<String> strOptionalNull = Optional.ofNullable(strNull);
どちらのパターンにも対応できる Optional のインスタンスを作成できた。
empty
中身が null な Optional を作る
中身が null であるとわかっている場合は empty がいい。
実際は ofNullable に null を指定した時と同じ動きをする。
Optional<String> strOptionalNull = Optional.empty();
// Optional<String> strOptionalNull = Optional.ofNullable(null); ← これと全く同じ