java - flatMap 的方法级通用类型

标签 java oop functional-programming stream lazy-evaluation

我目前正在开发惰性流的 SpecialList 实现,并且需要实现平面 map 功能。

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吗?为什么它给我这个错误?

最佳答案

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

() -> 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);
}

关于java - flatMap 的方法级通用类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58709492/

相关文章:

c# - 重新利用现有的 GUI,同时保留大部分相同的功能

javascript - 使用 JavaScript .map() 和 .filter() 按 lang 搜索作者/书籍数据模块

functional-programming - 有没有一种方法可以检查 F# 中一个模式中的嵌套选项值?

javascript - 如何重新创建 Underscore.js _.reduce 方法?

java - 一个只有静态方法的辅助类的声明应该是什么?

java - for循环变量声明中允许的类型?

javascript - 有人可以解释一下继承在 javascript 中是如何工作的吗

c# - 在 Func 体内调用 Func

java - Selenium 2 (WebDriver) + Java + Maven + Eclipse Hello World 程序问题

java - 我无法理解这个 Java 如何与我提供的参数一起工作