I have the following in my code:
Optional<Foo> optionalFoo = fooDAO.findByName(name);
Foo foo;
if(!optionalFoo.isPresent()) {
foo = fooDAO.addFoo(name);
} else {
foo = optionalFoo.get();
}
IntelliJ popped up a hint that said can be replaced with single expression in functional style. I tried replacing this block with:
Optional<Foo> optionalFoo = fooDAO.findByName(name);
Foo foo = optionalFoo.orElse(fooDAO.addFoo(name));
This caused tests to fail, as fooDAO.addFoo(name) is called regardless of whether or not the Optional is empty, and the logic within addFoo should not be run if the Foo already exists.
Is it possible to rewrite the original block functionally without calling fooDAO.addFoo(name) unless it's necessary?
You're looking for
orElseGet, which accepts aSupplierthat is only invoked when the value is not present:I think that
nameneeds to be effectively final for this to work.