how do call a polymorphic function from an agnostic function?

Posted by sds on Stack Overflow See other posts from Stack Overflow or by sds
Published on 2012-06-19T21:06:01Z Indexed on 2012/06/19 21:16 UTC
Read the original article Hit count: 249

Filed under:
|

I have a method foo

void foo (String x) { ... }
void foo (Integer x) { ... }

and I want to call it from a method which does not care about the argument:

void bar (Iterable i) {
  ...
  for (Object x : i) foo(x); // this is the only time i is used
  ...
}

the code above complains that that foo(Object) is not defined and when I add

void foo (Object x) { throw new Exception; }

then bar(Iterable<String>) calls that instead of foo(String) and throws the exception.

How do I avoid having two textually identical definitions of bar(Iterable<String>) and bar(Iterable<Integer>)?

I thought I would be able to get away with something like

<T> void bar (Iterable<T> i) {
  ...
  for (T x : i) foo(x); // this is the only time i is used
  ...
}

but then I get cannot find foo(T) error.

© Stack Overflow or respective owner

Related posts about java

Related posts about oop