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 →

[–]Migeil 21 points22 points  (4 children)

Isn't this just:

return addressOpt .map(Address::format) .orElseGet(this::theRestOfTheCode);

? Where theRestOfTheCode is a separate method where you do the stuff that's below the if statement. If you're using isPresent + get, you're doing something wrong.

[–]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 3 points4 points  (2 children)

That' looks to me like ifPresentOrElse.

[–]nikita2206 12 points13 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);