7

Let's consider the following class

class A{
    void met(int i){
       //do somthing
    }
}

and let's consider that we have an optional object of this class like:

Optional<A> a;

is it possible to call the method met on the object a without the need to check whether a refers to a full object or just empty (null). Something like:

a.map(A::met(5));

Unfortunately this code doesn't compile. How can this be done?

3
  • What do you expect to happen when a is empty? Commented Dec 17, 2014 at 9:56
  • the method will not be called Commented Dec 17, 2014 at 9:58
  • so as if this line of code a.map(A::met(5)); doesn't exist Commented Dec 17, 2014 at 10:00

1 Answer 1

12

There are two reasons why this can't work:

a.map(A::met(5));
  1. met returns nothing, and map must map the input Optional to an output Optional.
  2. method references don't take arguments, so you should use a lambda expression.

What you need is :

a.ifPresent(x->x.met(5));

Another option :

a.orElse(new A()).met(5);

This will execute met(5) on a dummy instance if a is empty, so it's probably not the best way.

Sign up to request clarification or add additional context in comments.

2 Comments

@Anas It's just an arbitrary variable name whose type is A. It's a way to refer to the instance held by your Optional<A>
Depending on semantics, the latter option could work well with the Null Object pattern.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.