5
0

More than 3 years have passed since last update.

Javaのnull合体演算子

Posted at

Javaにnull合体演算子が無いのでイケてないなあと思いつつ
Util関数を用意する次第

名称をcoalesceとして大体SQLの関数と同じ感じで使えるかなと

public final class Utils {
    @SafeVarargs
    public static <T> T coalesce(T... value) {
        for (T v : value) {
            if (v != null) {
                return v;
            }
        }
        return null;
    }
}
    public static void main() {
        String foo = null;
        String bar = null;
        String hoge = Utils.coalesce(foo, bar, "huga");
        System.out.println(hoge);
    }

でも正直なところC#のような??演算子が使いたいのです。

5
0
1

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
5
0