0

What is the best way to create a generic method that acts differently depending on the given type without using if statements that check what type is that?

For instance, how to create an Add<T>(T x, T y) method that returns x + y if T is Integer and x.add(y) if T is BigInteger, without checking if class of T is BigInteger or not.

  • Make `add(T x, T y)` an interface and have different implementation for each type. – c0der Apr 21 '18 at 10:11
  • You need to provide something which implements the operation you want, e.g. a `BinaryOperation`. – Andy Turner Apr 21 '18 at 10:14
  • 3
    That's not a use case of generics. Generic methods will do the _same_ thing (at least on a high level) regardless of the type. – Sweeper Apr 21 '18 at 10:21
  • Update: The reason I don't use _method overloading_ or _interface implementation_ is that the type I'm working with is defined by user input, so it is _unknown_ to me on the compilation stage. Please, let me know if I'm wrong and these methods can be used in such case or if there are other methods you can think of. What would you personally do? – Maristo-Tero Apr 21 '18 at 14:56

1 Answers1

3

There is no such feature for generic type parameters.

You might be looking for method overloading: Java allows you to create multiple methods with the same name, as long as they have different parameter types (and/or a different number of parameters). So you can write two or more methods with different implementations like this:

public Integer add(Integer i, Integer j) {
    // do stuff
}

public BigInteger add(BigInteger i, BigInteger j) {
    // do other stuff
}

When you call add, the compiler will then decide which of these methods to pick by checking the types of the arguments you passed.