FlatMap的方法级别通用键入

问题描述 投票:0回答:1

我目前正在研究惰性流的SpecialList实现,并且需要实现平面图功能。

public <R> SpecialList<R> flatMap(Function<T, SpecialList<R>> mapper) {
    return new SpecialList<R>(() -> mapper.apply(this.content));
}

这意味着我将接受类型为T的函数并返回类型为R的SpecialList。

但是,我遇到此错误:

SpecialList.java:43: error: no suitable constructor found for SpecialList(()->mapper[...]y(ts))
        return new SpecialList<R>(() -> mapper.apply(this.content));
               ^
    constructor SpecialList.SpecialList(R) is not applicable
      (argument mismatch; R is not a functional interface)
    constructor SpecialList.SpecialList(Supplier<R>) is not applicable
      (argument mismatch; bad return type in lambda expression
          SpecialList<R> cannot be converted to R)
  where R,T are type-variables:
    R extends Object declared in method <R>flatMap(Function<T,SpecialList<R>>)
    T extends Object declared in class SpecialList
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error

我有一个SpecialList()构造函数接受一个值,但是由于我的返回类型现在是'R',所以它似乎不起作用,并且他们说找不到合适的构造函数。

难道不是要替换'R'类型并在构造函数中成为T吗?为什么会给我这个错误?

java oop functional-programming stream lazy-evaluation
1个回答
0
投票

问题来自传递给构造函数的参数:

[() -> mapper.apply(this.content)的类型为Supplier<SpecialList<R>>,而不是R都不是Specialist<R>

很难理解您的意图到底是什么,但是如果您只是这样重写方法,则应编译该方法:

public <T, R> SpecialList<R> flatMap(Function<T, SpecialList<R>> mapper) {
    return mapper.apply(this.content);
}
© www.soinside.com 2019 - 2024. All rights reserved.