fhomovc
fhomovc

Reputation: 301

Access variable name in lambda function

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

Answers (1)

Roland
Roland

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

Related Questions