2

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?

3
  • do you just want to return the value of it.name? or do you actually want something like a supplier or similar that will return the name, when you access the supplier? (something like a lazy evaluation?) Commented Feb 20, 2019 at 16:24
  • Hi @Roland I want the name of the variable, not a property called "name". So for the first case it would be map.add(someClassVariable, "someClassVariable") Commented Feb 20, 2019 at 16:29
  • ah ok... now I got you... interesting... this doesn't seem to work yet, even though ::someClassVariable.name would... what are you trying to accomplish that way? maybe there is another approach too... I mean: now you manually put all the variables into the list... if that becomes more dynamic maybe also the rest will solve itself more easily? ;-) Commented Feb 20, 2019 at 16:37

1 Answer 1

3

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nice approach ;-) Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.