这样做的时候
Stream.of(1, 32, 12, 15, 23).map(Integer::toString);
Run Code Online (Sandbox Code Playgroud)
我得到一个模糊的类型错误.可以理解的是,编译器无法分辨我的意思toString(int)或toString()来自Integer.
当不使用方法引用时,我可能已经通过显式转换或者写出泛型的长手程来解决这个问题,但是如何让编译器知道我的意思呢?我可以使用什么语法(如果有的话)来明确?
是否有一种简便的方法来获取对本地静态方法的方法引用,就像this调用方法时可以删除关键字或类前缀一样?
显而易见的是使用::myStaticMethod但似乎无法编译:
class MyClass {
static void myStaticMethod () {}
static Runnable runner = ::myStaticMethod; // doesn't compile
// requires MyClass prefix despite being in the same class
}
Run Code Online (Sandbox Code Playgroud) 在以下代码中,
class IncWrapper<T> (val wrapped: T, val base: Int) {
fun incFunction(increment: Int, func: T.(Int) -> Int): Int {
return increment + wrapped.func(base)
}
}
class ClassWithIndecentlyLongName {
fun square(x: Int) = x * x
}
fun main() {
val wrapper = IncWrapper(ClassWithIndecentlyLongName(), 2)
val computed = wrapper.incFunction(1, ClassWithIndecentlyLongName::square)
println(computed)
}
Run Code Online (Sandbox Code Playgroud)
我们传递了对包装类方法的引用ClassWithIndecentlyLongName。由于在调用站点上知道此类应作为方法的接收者,因此再次传递该类的名称似乎很尴尬/多余。我希望有些事情::square能奏效,但事实并非如此。如果缺少此功能,可能是什么原因?
(这个问题源于试图重构一些冗长的Java代码,将一类的许多字段转换为另一类的代码。)