在 Kotlin 中引用特定实例的方法 [英] Reference to method of a particular instance in Kotlin
问题描述
在 Java 8 中,我们可以引用类的实例的方法.举个例子
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) }
推荐答案
从 Kotlin 1.1 开始,你可以使用 绑定可调用引用来做到这一点:
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屋!