Issue
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
public interface Calculator<T> {
T operation(T n1, T... n2); //this is where the optional parameter comes in
}
Main.java
public static void main(String[] args) {
Calculator<Integer> addition = (n1, n2) -> n1 + n2; //this gives an error
}
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?
Solution
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
Answered By - dreamcrash
Answer Checked By - Marie Seifert (JavaFixing Admin)