Reputation: 193
I'm coming from C# world and I'm having troubles using generics in Java. For some reason, Java complains about not being able to convert my types. Here's my code
public <T1, T2> ArrayList<T2> convert(List<T1> list, Function<T1, T2> function) {
ArrayList<T2> result = new ArrayList<T2>();
for (T1 source : list) {
T2 output = function.apply(source);
result.add(output);
}
return result;
}
public SomeType convertSomeType(SourceType input){
.....
return ....
}
and call it something like:
List<SourceType> list...
SomeType result = convert(list, this::convertSomeType)
I get Bad return type in method reference. Cannot convert SomeType to T2.
I also tried specifying generic parameters like so: List list... SomeType result = convert(list, this::convertSomeType)
but it didn't help. What am I doing wrong here?
Upvotes: 0
Views: 757
Reputation: 220877
Your method returns an ArrayList<T2>
(I'm assuming Tm
is a typo), not T2
:
// Your version, doesn't work:
SomeType result = convert(list, this::convertSomeType)
// This works:
List<SomeType> result = convert(list, this::convertSomeType)
Also, you should make that convert()
method follow PECS:
public <T1, T2> ArrayList<T2> convert(
List<? extends T1> list,
Function<? super T1, ? extends T2> function
);
Upvotes: 1