Vikram Bhat
Vikram Bhat

Reputation: 13

Compile error when using Java generic types with functional interface

I'm trying to use a Java functional interface with generic types, but the code does not compile and I'm at a loss to understand why. Here's the simplified version of the code:

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;

public class TestClass <T extends Number> {

    Function<List<T>, Integer> fun;

    public  void testFun (List<T> x) {
        List<Number> ln = new ArrayList<>();
        fun.apply(ln);     // error: incompatible types: List<Number> cannot be converted to List<T>
        testApply(ln);     // This is similar to the code above, but compiles fine
    }

    public <M extends Number> Integer testApply(List<M> x) {
        return 0;
    }
}

The error is indicated in the code. Any pointers about what I'm doing wrong?

Upvotes: 1

Views: 49

Answers (1)

Eran
Eran

Reputation: 393811

If you instantiate your class, for example, with:

TestClass<Integer> t = new TestClass<>();

the type of fun would be:

Function<List<Integer>, Integer>

and you can't pass a List<Number> to its apply method.

You can change:

List<Number> ln = new ArrayList<>();

to:

List<T> ln = new ArrayList<>();

to eliminate the error.

Upvotes: 2

Related Questions