In an interview, I was asked to write a function using Generics
that adds the numbers and Strings passed to it. The number could be Integer, Double, etc.
If 2 strings are passed to the function, it should append the strings. Finally, the added result should be returned.
I used Lambda as mentioned below.
public class WorkAround {
public static void main(String[] args) {
MyAdd myAdd = new MyAdd();
System.out.println("Adding Integers: " + myAdd.add(1, 2, (a,b) -> a+ b));
System.out.println("Adding Double: " + myAdd.add(1.2, 1.2, (a,b) -> a+ b));
System.out.println("Adding String: " + myAdd.add("James ", "Bond", (a,b) -> a + b));
}
}
class MyAdd {
public <T> T add(T a, T b, BinaryOperator<T> operation) {
return operation.apply(a, b);
}
}
Output:
Adding Integers: 3
Adding Double: 2.4
Adding String: James Bond
But then, I was asked to achieve the same result with Generics alone. Something like the below code snippet.
public class Trial {
public static void main(String[] args) {
MyAdd myAdd = new MyAdd();
System.out.println("Adding Integers: " + myAdd.add(1, 2));
System.out.println("Adding Double: " + myAdd.add(1.2, 1.2));
System.out.println("Adding String: " + myAdd.add("James ", "Bond"));
}
}
class MyAdd {
public <T> T add(T a, T b) {
return a + b;
}
}
Obviously, this did not work because of the following.
The operator + is undefined for the argument type(s) T, T
I found this thread the closet to my question. But that question did not handle Strings. Is there any other way that I might be missing?