Reputation: 301
I'm trying to access the name of a variable inside an iterator
listOf(someClassVariable, anotherClassVariable, yetAnotherClassVariable).forEach {
if (it.foo()) {
map.add(it, ::it.name)
}
}
but getting unsupported [references to variables aren't supported yet]
error at ::it.name
. Any ideas/workarounds?
Upvotes: 2
Views: 427
Reputation: 23252
You could do it vice-versa, i.e. having a list of references to your class variables and iterate over them and then get the actual value by calling invoke on it:
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)
}
Upvotes: 3