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?

More than 1 year has passed since last update.

【Java】Optionalの使い方を勘違いしてた話

Last updated at Posted at 2023-02-21

本日業務にてOptionalについて勘違いをしていたことに気付いたのでメモ。
Javaを書いていると、nullの安全性の観点からOptionalを使うことは大事だなと思いながらも、完全には理解できておらず、、

勘違いしていたケース

Jsonとマッピングする用のRequestBodyのクラスにて、以下のような定義をしていた。

Request.java
@Data
Public class Request {
    Integer hogeId;
    String hogeName;
    Optional<Integer> maxLength; // Optionalで定義
} 

上記のケースにて、リクエストで飛ばしたmaxLengthはOptionalでラップされていなかった。
その後request.getMaxLength().isPresent()という書き方をするとヌルポが発生し、気付いた。
getMaxLengthメンバ変数がnullになっていた。。
勝手にこの書き方でいけると思ってた。

実際には、この書き方ではOptionalにラップできないらしい。
Jsonとのマッピングがされないみたい。

書き直した

以下のように書き直した。

Request.java
@Data
Public class Request {
    Integer hogeId;
    String hogeName;
    Integer maxLength; // Optionalやめた
    public Optional<Integer> getMaxLength() {
        // getterでOptional型で返すようにした
        return Optional.ofNullable(this.maxLength);
    }
} 

上記のように書くことで、無事Optional型にできた。
lombokにて、@Dataによりgetterが自動生成されるが、上記のように設定すると自動生成されないらしい。

ただ、このようにRequestBodyでラップせず、Serviceクラス内でラップするのでも良いのではないかとは思うがどうなのか。。

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?