这样做的时候
Stream.of(1, 32, 12, 15, 23).map(Integer::toString);
Run Code Online (Sandbox Code Playgroud)
我得到一个模糊的类型错误.可以理解的是,编译器无法分辨我的意思toString(int)或toString()来自Integer.
当不使用方法引用时,我可能已经通过显式转换或者写出泛型的长手程来解决这个问题,但是如何让编译器知道我的意思呢?我可以使用什么语法(如果有的话)来明确?
我错过了什么?为什么我必须在Object::toString下面使用而不是Integer::toString?它与带有泛型的类型擦除有什么关系吗?
Arrays.asList(1,2,3).stream().map(Integer::toString).forEach(System.out::println); //Won't compile
Arrays.asList(1,2,3).stream().map(Object::toString).forEach(System.out::println); //Compiles and runs fine
Run Code Online (Sandbox Code Playgroud)