Hello,
Recently a colleague of mine encountered some strange behaviour when unittesting some code. Using a lambda stream with findFirst().orElse(method-call), shows that het method-call is ALWAYS executed, even if findFirst() returns a value.
Optional<Foo> opt = ...
Foo x = opt.orElse( new Foo() );
Foo y = opt.orElseGet( Foo::new );
If opt
doesn't contain a value, the two are equivalent.
But if opt
does contain a value, the orElse will create new Foo(), where the orElseGet won't.
orElse takes a value, thus the new Foo will be created when calling the orElse method. orElse will determine that a value is present in opt
, ignoring the newly created Foo.
orElseGet takes a Supplier wich can create a new Foo, but will not when opt
contains a value.
In my opinion the Optional.orElse should never be used with a method call, and I think it should be added as a sonarrule. When using orElse with a method call, the sonar rule could advice to use Optional.orElseGet.
Does anyone agree, or object? Any other perspective on this matter?
Kind Regards,
Erik Loosman