引用Kotlin中特定实例的方法 [英] Reference to method of a particular instance in Kotlin
问题描述
在Java 8中,我们可以引用Class实例的方法.这是一个例子
In Java 8 we can have a reference to a method of a Class' instance. Here's an example
Function1<Integer, Object> ref = a::getItem;
a是具有方法Object getItem(int i)
的类Adapter
的实例.
a is an instance of the class Adapter
that has the method Object getItem(int i)
.
我们可以在Kotlin中做同样的事情吗?我尝试了相同的语法,但没有成功.到目前为止,我只能创建一个扩展方法引用,如下所示:
Can we do the same in Kotlin? I tried the same syntax without success. So far I was only able to create an extension method reference like so:
val ref: Adapter.(Int) -> Any = Adapter::getItem
但是在这里我仍然需要Adapter
的实例来调用它.我看到的另一种替代方式是定义这样的lambda:
But here I still need an instance of an Adapter
to invoke it. The other alterantive I see is defining a lambda like this:
val ref: (Int) -> Any = { a.getItem(it) }
推荐答案
Since Kotlin 1.1, you can use bound callable references to do that:
val f = a::getItem
list.forEach(myObject::myMethod)
早期的Kotlin版本没有此功能,并且除了这些简单的案例.
Earlier Kotlin versions don't have this feature and require you to make a lambda every time except for these simple cases.
这篇关于引用Kotlin中特定实例的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!