Java8-显式类型如何匹配一个变体-而不是其他类型? [英] Java8 - How does explicit type matches one variant - not other type?
问题描述
我有一个简单的代码段,如下所示.我提到了此
I have a simple snippet as below. I referred this
List<Document> list = new LinkedList<Document>();
FindIterable<Document> itr = collection.find(findQuery)
.forEach((Document doc) -> list.add(doc));
return list;
它编译没有任何问题.
It compiles without any issues.
- 我猜我们是在告诉编译器
doc
是Document
类型. 为什么需要它?
- I guess that we are telling compiler that
doc
is of typeDocument
. Why is it needed?
但是,如果我执行以下操作,则会引发模棱两可的错误.我提到了此但无法准确地联系和理解.
But If I do the below, it throws ambiguous error. I referred this But couldn't relate and understand exactly.
collection.find(findQuery).forEach(list::add);
-
有人可以解释为什么第二个语句不起作用吗?
有没有更好的方式来编写第一个[工作的] ?
Java版本:1.8.0_231
Java version: 1.8.0_231
导入语句:
import java.util.List;
import java.util.Optional;
import com.mongodb.client.FindIterable;
import org.bson.Document;
推荐答案
FindIterable
继承了两个forEach
方法:
java.lang.Iterable.forEach(Consumer<? super T>)
您可以用其中任何一个重写参数
You could rewrite your paramter with either
Consumer<Document> consumer = documents::add;
Block<Document> block = list::add;
任何一个都可以.这些也将起作用:
And either will work. These too will work:
.forEach((Consumer<Document>) doc -> list.add(doc))
.forEach((Consumer<Document>) list::add);
但是,当您调用forEach(list::add)
或forEach(doc -> list.add(doc))
时,编译器无法选择哪个重载将确定方法引用的目标类型(因为该表达式在该上下文中与两者兼容).
However, when you call forEach(list::add)
or forEach(doc -> list.add(doc))
, the compiler is unable to pick which overload will determine the method reference's target type (because the expression is compatible with both in that context).
现在,我不确定100%为什么.forEach((Document doc) -> list.add(doc))
成功选择/链接Consumer<Document>
的签名而不是Block<? super Document>
的签名,我推测这与通用范围有关(但是我还在继续阅读).
Now, I'm not 100% sure why .forEach((Document doc) -> list.add(doc))
successfully selects/links the signature of Consumer<Document>
instead of the one with Block<? super Document>
, I'm surmizing it has to do with the generic bounds (but I'm still reading on this).
因为Block<? super Document>
版本已被弃用,所以您的选择应该很容易.
The choice for you should be easy because the Block<? super Document>
version is deprecated.
这篇关于Java8-显式类型如何匹配一个变体-而不是其他类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!