为了测试函数接口Function的compose()和andThen()方法,我做了一个简单的代码:
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;
}
}
但是正如您所看到的,这段代码将无法编译。给定原因:不存在类型变量(v) v的实例,因此Function符合Trans。
关于通配符中extends和super的差异的多个主题,我理解它们在列表中的使用,但不确定为什么它不能在这里编译。
是否有任何方法可以在方法testCompose()中返回一个对象Trans,或者必须返回一个函数来让代码编译?
不,此代码不正确。testCompose()
返回的对象不实现Trans
;它是一个匿名lambda helper类型,不能强制转换为Trans
。
testCompose()
方法应该声明为返回Function<File, File>
,因为这是唯一实现的接口。