General functional interface and method reference corrupted by Erasure type

I have the following general functional interface:

@FunctionalInterface
public interface FooInterface<T> {
    void bar(T arg);
}

And this descendant of a descendant of ArrayList:

public class FooList<T> extends ArrayList<FooInterface<T>> {
    public void doFoo(T arg) {
        for(Iterator<FooInterface<T>> i = iterator(); i.hasNext(); ) {
            i.next().bar(arg);
        }
    }
}

Now I am writing this code using method references and erasing the styles:

protected void doFoo(Object arg) { }

private void doStuff() {                                         
    FooInterface f = this::doFoo; 

    List<FooInterface> list = new ArrayList<>();
    list.add(f2);                 
    list.add(this::doFoo);        

    FooList list2 = new FooList();
    list2.add(f2);                
    list2.add(this::doFoo);    // <-- Compiler chokes here, complaining that this is not a FunctionalInterface
}                                        

It puzzles me. Why would the compiler be fine with me by assigning this :: doFoo to the variable FooInterface and calling List.add () in the first part of the code, only to reject the call of the same add () method from the class that descends from ArrayList

Something funky seems to be happening with type erasure in my descendant class, but what? This is mistake? I did not support something?

+4
source share
2 answers

FooList ( ) . 4.8. Raw Types :

( ) - () .

, raw FooList ArrayList, add Object.

Object , . :

Object f = this::doFoo;

:

error: no suitable method found for add(this::doFoo)
    list2.add(this::doFoo);    // <-- Compiler chokes here, complaining that this is not a FunctionalInterface
         ^
    method Collection.add(Object) is not applicable
      (argument mismatch; Object is not a functional interface)

"" - - , :

public class FooList<T> extends ArrayList<FooInterface<T>> {
    @Override
    public boolean add(FooInterface<T> e) {
        return super.add(e);
    }
    ...
}

, , "", , . .

+4

FooList.

FooList list2 = new FooList();

FooList<FooInterface> list2 = new FooList();

.

0

All Articles