2

In order to test compose() and andThen() methods of the funtional interface Function I did a simple code :

public class Test {    
    public Trans testCompose() {
        return new T1().compose(new T2());
    }
}

interface Trans extends Function<File, File> {
}

class T1 implements Trans {
    @Override
    public File apply(File file) {
        return null;
    }
}

class T2 implements Trans {
    @Override
    public File apply(File file) {
        return null;
    }
}

But as you can see this code will not compile. Given reason : no instance(s) of type variable(v) V exists so that Function conform to Trans.

Following multiple subjects about the difference of extends and super in wildcards I understand the use of them in a list, but not really sure why it cannot compile here.

Is there any way to keep returning an object Trans in the method testCompose() or should it necessarily return a Function to let the code compile ?

Community
  • 1
  • 1
Rizen
  • 121
  • 4

1 Answers1

4

No, this code is incorrect. The object returned by testCompose() does not implement Trans; it is an anonymous lambda helper type, and can't be cast to Trans.

The testCompose() method should be declared as returning Function<File, File>, as that is the only implemented interface.

erickson
  • 249,448
  • 50
  • 371
  • 469