private void foo(int a, int b) {
// do something
System.out.println(add(a, b));
// do something else
}
private void bar(String a, String b) {
// do something
System.out.println(add(a, b));
// do something else
}
private int add(int a, int b) {
return a b;
}
private String add(String a, String b) {
return a.concat(b);
}
Is it possible to merge duplicated logic in foo and bar into one function?
e.g.
private <T> void baz(T a, T b) {
// do something
System.out.println(add(a, b));
// do something else
}
CodePudding user response:
Your baz
code is valid, but won't work for your case because generic parameters get reduced to Object
at runtime, so it needs to be resolved at compile time. To be able to do that, you'd need a common interface like Addable
, then you could declare it
private <T extends Addable> void baz(T a, T b) {
// do something
System.out.println(add(a, b));
// do something else
}
but you wouldn't be able to call it with int
or String
because those don't implement Addable
; you could wrap them, but not much gained in what you're trying to do.
So in short: no, not possible; you need to design around this.
interface Addable<T extends Addable<T>> { T add(T to Add); }
class IntAddable implements Addable<IntAddable> {
Integer value;
Integer add(IntAddable toAdd {
return new IntAddable(value to Add.value);
}
}
IntAddable a = new IntAddable(1);
IntAddable b = new IntAddable(2);
IntAddable sum = baz(a, b);
// assuming an analogue class for String
StringAddable concatted = baz(s1, s2);
CodePudding user response:
No, you can't do this as you've written it.
The biggest blocker (as I see it) is that add(String,String) returns an object, but add(int,int) returns a primative(int), so there's a problem with return type.
But I think you are over complicating things here. Why can't the two add functions could stand on their own? Do you really need a generic baz
function?