またしょーもない所で詰まったので備忘録がてらにメモ。
以下のプログラムで[hoge]内の[fuga]には何が代入されているかという問題。
例: Sample1.java
package test; import java.util.Optional; public class Sample1 { public static void main(String[] args) { Hoge hoge = new Hoge(); Optional.of(hoge).orElse(hoge.withFuga("bar")); System.out.print(hoge.getFuga()); } public static class Hoge { private String fuga = "foo"; public Hoge withFuga(String fuga) { this.fuga = fuga; return this; } public String getFuga() { return fuga; } } }
[hoge.getFuga()]の出力結果は[fooの文字列]である……と言いたい所だが[barの文字列]である。
実はこのプログラム、よく見ると[Optional.orElse()]に渡す時点でwithFuga()が実行されているためである。
もし本当に[Optional]でnullの場合だけ[barの文字列]を[foo]にセットしたい場合には[Optional.orElseGet()]を使用する。
例: Sample2.java
package test; import java.util.Optional; public class Sample2 { public static void main(String[] args) { Hoge hoge = new Hoge(); Optional.of(hoge).orElseGet(() -> hoge.withFuga("bar")); System.out.print(hoge.getFuga()); } public static class Hoge { private String fuga = "foo"; public Hoge withFuga(String fuga) { this.fuga = fuga; return this; } public String getFuga() { return fuga; } } }
[hoge.getFuga()]の出力結果は[fooの文字列]である