Is using Optional.ofNullable as a replacement for the ternary operator a good practice?

前端 未结 6 2127
Happy的楠姐
Happy的楠姐 2020-12-09 04:50

Consider the usage of this expression:

String hi = Optional.ofNullable(sayHi()).orElse(\"-\");

which effectively corresponds to this ternar

6条回答
  •  北海茫月
    2020-12-09 05:37

    In JDK 9 or later, use this:

    String hi = Objects.requireNonNullElse(sayHi(), "-");
    

    This avoids having to repeat sayHi() if a ternary operator is used, or to assign its value to a local variable that is reused within the ternary. It might be a small improvement. It also sidesteps the question of whether to use Optional. :-)

提交回复
热议问题