如何修复方法引用上的歧义类型(整数的 toString)? [英] How to fix ambiguous type on method reference (toString of an Integer)?
问题描述
这样做时
Stream.of(1, 32, 12, 15, 23).map(Integer::toString);
我收到一个不明确的类型错误.可以理解的是,编译器无法判断我的意思是 toString(int)
还是 toString()
来自 Integer
.
I get an ambiguous type error. Understandably, the compiler can't tell if I mean toString(int)
or toString()
from Integer
.
当不使用方法引用时,我可能已经通过显式转换或写出泛型来摆脱这种情况,但是我如何让编译器知道我在这里的意思?我可以使用什么语法(如果有)来明确表示?
When not using a method reference, I might have gotten out of this with an explicit cast or write out the generics long hand, but how can I let the compiler know what I mean here? What syntax (if any) can I use to make in unambiguous?
推荐答案
没有办法使方法引用明确;简单地说,方法引用是一种仅支持无歧义方法引用的功能.所以你有两个解决方案:
There is no way to make method references unambiguous; simply said, method references are a feature that is just supported for unambiguous method references only. So you have two solutions:
使用 lambda 表达式:
use a lambda expression:
Stream.of(1, 32, 12, 15, 23).map(i->Integer.toString(i));
(至少是我的首选)当源仅由原始 int
值组成时,使用原始 int
值流:
(preferred, at least by me) Use a stream of primitive int
values when the source consists of primitive int
values only:
IntStream.of(1, 32, 12, 15, 23).mapToObj(Integer::toString);
这将使用静态 Integer.toString(int)
方法来使用 int
值.
This will use the static Integer.toString(int)
method for consuming the int
values.
这篇关于如何修复方法引用上的歧义类型(整数的 toString)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!