public interface Calculator<T> {
T operation(T n1, T .. n2); //this is where the optional parameter comes in
}
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
public interface Calculator<T> {
T operation(T n1, T n2); //this is where the optional parameter comes in
}
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:
public static void main(String[] args) {
Calculator<Integer> addition = (n1, n2) -> n1 + Arrays.stream(n2).reduce(0, Integer::sum);
}
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:
public interface Calculator<T> {
T operation(T ...n);
}
In this way, the method operation
can accept 0, 1 ... N elements and even null
.
Then in your main:
Calculator<Integer> addition = n -> (n == null) ? 0 :
Arrays.stream(n).reduce(0, Integer::sum);
A running Example:
public class Main {
public static void main(String[] args) {
Calculator<Integer> addition = n -> (n == null) ? 0 : Arrays.stream(n).reduce(0, Integer::sum);
System.out.println(addition.operation(1, 2));
System.out.println(addition.operation(1));
System.out.println(addition.operation());
System.out.println(addition.operation(null));
}
}
Output:
3 // 1 + 2
1 // 1
0 // empty array
0 // null