Lambda函数中的访问变量名称

时间:2019-02-20 16:21:34

标签: android reflection kotlin

我正在尝试访问迭代器中的变量名

listOf(someClassVariable, anotherClassVariable, yetAnotherClassVariable).forEach {
    if (it.foo()) {
        map.add(it, ::it.name)
    }
}

但在unsupported [references to variables aren't supported yet]出现::it.name错误。有任何想法/解决方法吗?

1 个答案:

答案 0 :(得分:2)

反之亦然,即拥有对类变量的引用列表,并对其进行迭代,然后通过调用调用来获取实际值:

listOf(::someClassVariable, ::anotherClassVariable, ::yetAnotherClassVariable).forEach { varRef ->
    val varValue = varRef() // assignment optional... you can also just do it the way you want ;-)
    if (varValue.foo())
        map.add(varValue, varRef.name)
}