可能之前问过,但找不到。
我写了很多声明的形式:
if (bar.getFoo() != null) {
this.foo = bar.getFoo();
}
Run Code Online (Sandbox Code Playgroud)
我想到了三元运算符,但在我看来,这并没有让它变得更好:
this.foo = bar.getFoo() != null ? bar.getFoo() : this.foo;
Run Code Online (Sandbox Code Playgroud)
我的主要问题是在这两种情况下我都必须编写 bar.getFoo() 两次。当然我可以写一个辅助方法来解决这个问题,但我想知道是否有更优雅的解决方案。
不同于:避免 != null 语句,因为该问题不涉及将检查为 null 的值分配给值。
这避免了 if 语句并调用getFoo()一次。但是你必须输入this.foo两次:
this.foo = Objects.requireNonNullElse?(bar.getFoo(), this.foo);
Run Code Online (Sandbox Code Playgroud)