如何在方法引用(toString of Integer)上修复歧义类型? [英] How to fix ambiguous type on method reference (toString of an Integer)?

查看:232
本文介绍了如何在方法引用(toString of Integer)上修复歧义类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

执行此操作时

Stream.of(1, 32, 12, 15, 23).map(Integer::toString);

我收到一个模糊的类型错误。可以理解的是,编译器无法判断 toString(int) toString()是否来自整数

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:


  1. 使用lambda表达式:

  1. 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 of Integer)上修复歧义类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆