I cannot do this in Java:
Optional optStr = Optional.of(\"foo\");
String result;
optStr.ifPresent(s -> result = s);
The doc sa
If the code
Optional optStr = Optional.of("foo");
String result;
optStr.ifPresent(s -> result = s);
was legal, it still was useless, as the variable result
is not definitely assigned after the invocation of ifPresent
. Java does not allow reading local variables which are only conditionally initialized. So you would need an alternative value for result
for the case of an empty Optional
, e.g.:
Optional optStr = Optional.of("foo");
String result=null;// or any other default value
optStr.ifPresent(s -> result = s);
But then, if you have defined such a default/fall-back value, you can use the method intended for this purpose:
Optional optStr = Optional.of("foo");
String result=optStr.orElse(null /* or any other default value */);
When you say, you have to initialize more than one variable, it doesn’t change the fact that these variables need to be initialized in either case. Also, there is no benefit in performing the initialization of dependent variables inside a lambda expression passed to the Optional
as, after all, the Optional
carries only a single value. Everything dependent on that value can get determined after getting that value, independently of the Optional
:
Optional optStr = Optional.of("foo");
Type1 variable1;
Type2 variable2;
Type3 variable3;
if(optStr.isPresent()) {
String s=optStr.get();
// determine and assign variable1, variable2, variable3 based on s
} else {
// assign defaults/fall-backs to variable1, variable2, variable3
}
Note that even if your variables are already pre-initialized and you want to mutate them, using if(optional.isPresent()) /* local modifications */
is the simplest way to do it. There’s nothing that works better when you replace this idiom with a lambda expression.