Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to pass variable in code after the dot

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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)?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading