如何将属性获取器作为函数类型传递给另一个函数 [英] How can I pass property getter as a function type to another function
问题描述
如何将属性获取器传递给接受函数类型的函数?
How can I pass property getter to a function that accepts function type?
以下是我想要实现的示例:
Here is an example of what I want achieve:
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
)来引用吸气剂.
You can reference the getter by writing ::test
(or this::test
).
编写test::get
时,实际上是在String
上引用get
方法.该方法获取一个索引并返回该索引处的字符.
When you write test::get
, you are actually referencing the get
method on String
. That method takes an index and returns the character at that index.
如果该属性是var
,并且您想要引用其setter,则可以编写::test::set
.
If the property was a var
and you want a reference to its setter, you can write ::test::set
.
有关属性引用的更多信息,请参见此处: https://kotlinlang.org/docs/reference/reflection.html#bound-function-and-property-references-since-11
For more info on property references, see here: https://kotlinlang.org/docs/reference/reflection.html#bound-function-and-property-references-since-11
这篇关于如何将属性获取器作为函数类型传递给另一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!