Arya
Arya

Reputation: 8965

calling method with Optional parameter in Java 8

I have the following method

public static Boolean test(String str, Optional<Boolean> test) {


}

but if I try to call it like

test("hello")

I get an error that the method requires two parameters.

Shouldn't the Optional parameter allow to me call the test method without providing the Optional parameter?

Upvotes: 1

Views: 32575

Answers (3)

davidxxx
davidxxx

Reputation: 131326

Optional is not a optional parameter as var-args is.
Optional is a container object which may or may not contain a non-null value.

So you could invoke the method as :

test("...", Optional.of(true));

or

test("...", Optional.empty());

Note that with var-args :

public static Boolean test(String str, Boolean... test) {    
 //...
}

this would be valid :

test("hello")

But var-args is not the correct way to pass an optional parameter as it conveys 0 or more objects and not 0 or 1 object.

Method overload is better :

public static Boolean test(String str, Boolean test) {
 // ...
}

public static Boolean test(String str) {
 // ...
}

In some other cases, the @Nullable constraints (JSR-380) may also be interesting.

Upvotes: 10

Tiberiu Zulean
Tiberiu Zulean

Reputation: 172

In short, no. Optional is a class and in Java you must pass the exact number of parameters to a method just like it is defined.

The only exception is when you put ... after the class object name in the method declaration.

public String test (String X, String... Y) { }

Which makes the second parameter be either zero or more.

Upvotes: 1

Mohamad Hatem
Mohamad Hatem

Reputation: 63

Try this

public static Boolean test(String str, Boolean ... test) {}

it will work with you

Upvotes: 0

Related Questions