adit
adit

Reputation: 39

Pass optional objects as varags in parameter?

I want to pass multiple optional objects in function as varags ?

Optional<ab> ab = Optional.of(ab);
Optional<cd> cd = Optional.of(cd);
Optional<dc> dc = Optional.of(dc);
Optional<ba> ba = Optional.of(ba);
data(ab, cd, dc, ba);
data(Optional<Object>... objects){...}

I am getting error if i don this, any suggestion how can be proceed?

Upvotes: 0

Views: 65

Answers (1)

Anonymous
Anonymous

Reputation: 86276

It isn’t related to varargs. You can’t pass an Optional<SomeSpecificType> where an Optional<Object> is expected. They are not compatible.

Assume just (without varargs):

static void data(Optional<Object> object) {
    // …
}

Now if we try

    Optional<String> ab = Optional.of("");
    data(ab);

In my Eclipse I get this error message:

The method data(Optional<Object>) in the type MyClass is not applicable for the arguments (Optional<String>)

Java generics are defined with this restriction. You also cannot pass, for example a List<String> where a List<Object> is expected.

You can overcome the limitation by declaring the method generic too:

static <T> void data(Optional<T> object) {
    // …
}

Or just like this:

static void data(Optional<?> object) {
    // …
}

With any of these two declarations the call above is OK.

BTW, @HadiJ is correct in the comment: Optional is meant for return values for from methods that may or may not be there. They have very few other good uses, and as parameters is not one of them. It seems to me that for your use case you should just pass the arguments that are there and leave out those that aren’t. The your data method may receive a longer or shorter argument array, but will just have to handle all elements of the array without caring about Optional. And passing String, Integer, LocalDate, etc, to a method declared void data(Object... objs) is straightforward and poses no problem.

Upvotes: 1

Related Questions