Home > database >  constructing var name from string concatanation
constructing var name from string concatanation

Time:04-13

I'm not sure I worded the question correctly. I have a set of variables, that go like: STO1, STO2, STO3.....STO9; and I need to get the user to input the digit to store and to recall those memory addresses. So is there a way that the 'STO' be concatenated to the digit (1...9) to get to the var name? The var names are declared already. I just need to either store a value or retrieve it. I know that in other languages that is indirect addressing, I think.

Thanks in advance for any input.

Ray.

CodePudding user response:

If variables defined insisde the class (so they are properties) it can be done via Reflection Api.

class Example {
    var sto1 = "s1"
    var sto2 = "s2"
}

fun main() {
    val obj = Example()
    val userInput = "1"

    val prop = Example::class.memberProperties.find { it.name == "sto$userInput"}
    prop as KMutableProperty<*>
    //get value example
    println(prop.get(obj))

    //set value example
    prop.setter.call(obj, "new value")
    println(prop.get(obj))
}

In order to compile it you should add kotlin-reflect lib to your maven/gradle project.

  • Related