我目前正在开发惰性流的 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/