【问题标题】:Returning an Object when using compose() or andThen() from Function<V, R>从 Function<V, R> 使用 compose() 或 andThen() 时返回一个对象
【发布时间】:2016-09-29 04:17:20
【问题描述】:

为了测试功能接口 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;
    }
}

但正如您所见,这段代码无法编译。 给定原因:不存在类型 variable(v) V 的实例,因此 Function 符合 Trans。

multiple subjects 讨论通配符中extends 和super 的区别之后,我了解它们在列表中的使用,但不确定为什么它不能在这里编译。

有什么方法可以在 testCompose() 方法中继续返回一个对象 Trans 还是必须返回一个 Function 来让代码编译?

【问题讨论】:

    标签: java wildcard functional-interface


    【解决方案1】:

    不,此代码不正确。 testCompose()返回的对象没有实现Trans;它是一个匿名 lambda 助手类型,不能转换为 Trans

    testCompose() 方法应声明为返回 Function&lt;File, File&gt;,因为这是唯一实现的接口。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-18
      • 1970-01-01
      • 2021-08-23
      • 2019-10-20
      • 2011-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多