0

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?

Arya
  • 8,473
  • 27
  • 105
  • 175

3 Answers3

10

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.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • 1
    Note that `...` means `0 or more`, which makes `test` a `Boolean[]` and more than 1 `Boolean` can be passed into this method. – Mark Nov 04 '18 at 20:04
  • 2
    I wouldn't equate varargs with optional parameters. The appropriate thing to do here, if you don't want to pass the parameter, is to define an overload. – Andy Turner Nov 04 '18 at 20:10
  • @Andy Turner I agree too. My last sentence conveys that. About the overload, it is a way indeed. And in some other cases`@Nullable` may be a good alternative too. – davidxxx Nov 04 '18 at 20:13
  • @davidxxx it doesn't convey it. If you want to say to use an overload to pass 0 or 1 parameters, say that, and show an example; and ditch the varargs stuff, or at least put it below the overloads stuff. – Andy Turner Nov 04 '18 at 20:14
  • @Andy Turner Agree again. Thrown out or almost. – davidxxx Nov 04 '18 at 20:22
1

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.

Tiberiu Zulean
  • 162
  • 3
  • 13
  • To be more precise: `Optional` is a class *like any other*. It is not defined in the language specification, and thus it is not handled in any way that is special. – Andy Turner Nov 04 '18 at 20:12
  • @AndyTurner Exactly, good point! As a method parameter, it is handled in the same way as either another class or a primitive. – Tiberiu Zulean Nov 04 '18 at 20:17
0

Try this

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

it will work with you

Mohamad Hatem
  • 53
  • 1
  • 7