如何将 属性 getter 作为函数类型传递给另一个函数

How can I pass property getter as a function type to another function

如何将 属性 getter 传递给接受函数类型的函数?

这是我想要实现的示例:

class Test {
    val test: String
        get() = "lol"

    fun testFun(func: ()->String) {
        // invoke it here
    }

    fun callTest() {
        testFun(test::get) 
        // error: Type mismatch: inferred type is 
        // KFunction1<@ParameterName Int, Char> but () -> String was expected
    }
}

有办法吗?

您可以通过写::test(或this::test)来引用getter。

当你写test::get时,你实际上是在引用String上的get方法。该方法采用索引和 returns 该索引处的字符。

如果 属性 是一个 var 并且您想要引用它的 setter,您可以写 ::test::set.

有关 属性 参考资料的更多信息,请参阅此处:https://kotlinlang.org/docs/reference/reflection.html#bound-function-and-property-references-since-11

看来你在逻辑层面上做错了。

如果您正在重写变量的 get 方法,那么您可以通过此 get 方法访问它的值。因此,当您可以通过它姓名?

如前所述,您可以使用this::test来引用getter。或者,如果你有 kotlin-reflect,你可以做 this::test.getter

当您将字段作为函数传递时,它假定您指的是 getter。因此,如果您想要 setter,您有两个选择:

this::test::set

this::test.setter

后者,就像this::test.getter需要kotlin-reflect,否则程序会崩溃(使用Kotlin 1.2.50在本地测试)

但是,您可以通过其他方式获得 getter。但我建议您坚持使用 this::test,因为它更短。

你可以这样做:

this::something::get

something::get 它指的是字符串 class 中的方法,其中 returns 索引处的一个字符。作为参考,方法声明:

public override fun get(index: Int): Char

如果您不介意,就使用{ test }(例如testFun { test })。这将准确地转化为您的 () -> String。下一个最佳选择可能是 ::test(或 this::test),正如已经提到的那样。

第二个可能对性能的影响很小(可以忽略不计?)。我自己没有测试过,也没有找到任何有关它的消息来源。我之所以这样说,是因为下面的字节码是什么样子的。正因为这个问题,我问自己两者的区别: