Consider the usage of this expression:
String hi = Optional.ofNullable(sayHi()).orElse(\"-\");
which effectively corresponds to this ternar
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
. :-)