扩展表达式如 : () -> V 的 KPropertyX 接口是什么意思

What does it mean that KPropertyX interface which extends an expression like : () -> V

我把我的问题放在我在 Kotlin 源代码中看到的一个例子上。 这是 kotlin 中 K属性0 接口的声明:

public actual interface KProperty0<out V> : KProperty<V>, () -> V {

谁能解释一下我可以从中得到什么用法

() -> V

当我们扩展 class 或接口时,我们实际上继承了它的方法,属性 等。我不明白我可以用

做什么

() -> V

在这里做我自己的例子:

class Foo : () -> String {

        override fun invoke(): String {
        return "Bar"
        }   
    }

这允许你做:

 val result = Foo().invoke()

或者,正如评论中所指出的,您可以通过

直接调用
Foo()().

所以,经过更多的研究,我发现 invoke 方法是一个运算符函数,在这种情况下,它也是 lambda 函数(或任何函数)的一部分,所以使用接口编写等效的东西,你必须添加 operator 修饰符

类似于以下内容:

   interface Bar {
    operator fun invoke(): String
}

class Foobar : Bar {

    override operator fun invoke(): String {
        return "foo"
    }
}

本质上,这只是定义调用此方法时发生的情况

看起来像是使用 actual 修饰符的功能,您必须为 operator fun invoke().

明确指定它
public actual interface KProperty<out V> : KCallable<V>

public actual interface KProperty0<out V> : kotlin.reflect.KProperty<V>, () -> V {
   public actual fun get(): V

   public override abstract operator fun invoke(): V
}

public actual interface KProperty1<T, out V> : kotlin.reflect.KProperty<V>, (T) -> V {
   public actual fun get(receiver: T): V

   public override operator fun invoke(p1: T): V
}