如何将属性 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
}
}
有办法吗?
您可以通过编写来引用 getter::test
(or this::test
).
当你写的时候test::get
,你实际上引用的是get
方法上String
。该方法采用一个索引并返回该索引处的字符。
如果该房产是var
并且您想要对其设置器的引用,您可以编写::test::set
.
有关属性参考的更多信息,请参见此处:https://kotlinlang.org/docs/reference/reflection.html#bound-function-and-property-references-since-11 https://kotlinlang.org/docs/reference/reflection.html#bound-function-and-property-references-since-11
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)