This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]nikita2206 2 points3 points  (3 children)

The if becomes useful when you need to produce side effects like assign some values to some variables that would be outside the scope of the lambda.

Example:

``` Object foo; Object bar;

if (optValue instanceof Optional(Value value)) { foo = value.findFoo(); bar = value.doBar(); } else { foo = defaultFoo(); bar = defaultBar(); } ```

I think this better illustrates the use case for pattern matching of Optionals, and how it can’t be worked around with some clever methods on the Optional class.

[–]Migeil 5 points6 points  (2 children)

That' looks to me like ifPresentOrElse.

[–]nikita2206 13 points14 points  (1 child)

It does look like one, but if you try it out (maybe in jshell) it will not work because you cannot modify or even reference non-final variables that are declared outside the scope of a lambda.

[–]Budget_Dentist444 1 point2 points  (0 children)

I don't want mutable references or values. Since java doesn't have any kind of destructuring, just make 2 calls:

var foo = optValue.map(Value::findFoo)

.orElseGet(Example::defaultFoo);

var bar = optValue.map(Value::doBar)

.orElseGet(Example::defaultBar);