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.
test("hello", Optional.empty());- -Optionalis a poor substitute for overloading.Optionalmeans here.Optionalis another type of Java object...