Skip to content
Advertisement

Is it possible to make a generic functional interface with optional parameter(s)?

I’m trying to create a functional interface in Java with a single method (of course) that can take any type of parameter(s) and return any data type (i.e. a generic method).

This is what I have so far:

Calculator.java

JavaScript

Main.java

JavaScript

The error says:

bad operand types for binary operator ‘+’

  • Is it possible to create a generic functional interface with optional parameter(s) in Java?
  • If so, what am I doing wrong?

Advertisement

Answer

JavaScript

The error comes from the fact that you are trying to apply the operator + to a Integer and an Array of Integers. The following, for instance

JavaScript

would work fine, since you would be applying the operator + to two Integers.

If you want to keep the same Interface then you need to change you code in the main to:

JavaScript

Is it possible to create a generic functional interface with optional parameter(s) in Java?

From this SO Thread one can read:

varargs could do that (in a way). Other than that, all variables in the declaration of the method must be supplied. If you want a variable to be optional, you can overload the method using a signature which doesn’t require the parameter.

That being said, what you could do is something like:

JavaScript

In this way, the method operation can accept 0, 1 … N elements and even null.

Then in your main:

JavaScript

A running Example:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement