I have problem with Optional and I don't know how to handle it.
public void check(String name) {
if (name != null)
doSomething(name);
else
doMore();
}
How to change this if into Optional?
How to change this if into Optional? It might be better to take advantage of method overloading in this case, so that the check() method with no parameter calls doMore(), while the check() method with the @NonNull String name only accepts non-null Strings. Otherwise, follow either Eugene's or luk2302's suggestions.
Creating Optional objects Also, by using ofNullable , you can create an Optional object that may hold a null value: Optional<Soundcard> sc = Optional. ofNullable(soundcard); If soundcard were null, the resulting Optional object would be empty.
The reason why Optionals are so useful is because with Optionals it forces you to represent your data in such a way that you can't invoke a method from null . Without Optionals it's not only possible, it's extremely easy to. In other words, you avoid sloppy logic and stupid errors.
There is a very neat method for that, but present in jdk-9...
public void check(String name){
Optional.ofNullable(name)
.ifPresentOrElse(YourClass::doSomething, YourClass::doMore);
}
assuming doSomething
and doMore
are static methods... If not an instance should be used, like this::doSomething
or this::doMore
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With