Home > Enterprise >  how to pass variable in code after the dot
how to pass variable in code after the dot

Time:09-14

in Android I have something like R.string.whatever_text

instead to pass in a function R.string.whatever_text

fun pass(string: Int) {
getString(string)
}

I want to know a way to pass only whatever_text

ex

fun pass(genericString:String) {
getString(R.string.genericString)
}

Please notice the example of R.string.whatever_text is not relevant, I am speaking in general, want to achieve that can pass as a String a part of what i need instead to repeat long lines ex could have been NavigationDestination.whateverDestination.screenRoute or whatever code

CodePudding user response:

You could potentially use reflection for having the name of the field and match that to the generated static name of the variable. I don't think that is a good idea because:

Anything under R is a unique static integer autogenerated, so when you write

R.domain.humanIdentifier

You are actually just saying 124124125215.

So if you try to compose that number from R.string.${variable} you will only be creating a data type that is not the number.

And you cant know the number before hand neither because is created by a tool you dont have direct access (I think is called Android Automatic Tool or something like that).

If you cmd click the getString method you will see the argument there is a number.

If you insist, it would be something like this:

val field = ::R::class.memberProperties.firstOrNull {
    it.name == genericString
} ?: return
getString(field.getter as Int)

There are so many dangerous things on the above code that is not really worth it, and it opens further questions, like what is going to happen after the code is ofuscted (pro guard)?

  • Related