0

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?

user5080246
  • 193
  • 1
  • 11

1 Answers1

1

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
);
Community
  • 1
  • 1
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
  • yes, you're so right! I found my mistake out right after posting it but thanks for you answer! However, the error message should have been clearer :) – user5080246 Dec 12 '16 at 21:06
  • @user5080246: Yes indeed, the Java compiler often puts a side-effect of the actual error in the error message, which can be very confusing when using method references or lambdas... – Lukas Eder Dec 12 '16 at 21:07