0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Optionalを生成するメソッド(Java)】

Posted at

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); 

例2nullString 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); ← これと全く同じ
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?