Home > Blockchain >  Can you have the content of a string act as a val name in kotlin?
Can you have the content of a string act as a val name in kotlin?

Time:05-13

Is it possible to do something like

var myThemeVariable = "redTheme" //could be either redTheme, greenTheme, or blueTheme for example
context.setTheme(R.style.myThemeVariable) //sets theme to R.style.redTheme

instead of what i usually do

var myThemeVariable = "redTheme" //could be either redTheme, greenTheme, or blueTheme
when (myThemeVariable) 
{
"redTheme" -> context.setTheme(R.style.redTheme)
"greenTheme" -> context.setTheme(R.style.greenTheme)
"blueTheme" -> context.setTheme(R.style.blueTheme)
}

In this example it's not super cluttered, but in my actual code there's a lot more. My current solution is not only hard to understand, add to, or remove from; it's also (I imagine) unnecessarily computationally expensive. Is something akin to the first approach possible? If it's not, does any language have something like it? Thanks!

CodePudding user response:

Thanks y'all, in the end I searched about @blackapps' and @Haseeb Hassan Asif's recommendations and found this post so I ended up doing this :)

val themeResID = context.resources.getIdentifier((sharedPreferences.getString("theme", "default_standard")), "style", context.packageName) //get theme from shared preferences
context.setTheme(themeResID)

CodePudding user response:

getIdentifier uses reflection under the hood, so it has poor performance. If you're using it sparingly, like to set the theme once whenever a button is pressed, that performance difference will not be noticeable. But the code is overly complicated either way.

Just use your IDs directly like this. No Strings or when statements are necessary.

var myThemeVariable = R.style.redTheme // redTheme, greenTheme, or blueTheme

context.setTheme(myThemeVariable)
  • Related