Home > Enterprise >  Kotlin : How to insert a value of a variable in a name of another variable
Kotlin : How to insert a value of a variable in a name of another variable

Time:08-17

Sadly, I failed to find any answer to this question on SO or elsewhere.

I am studying Kotlin and Android development and I wonder how I can insert a value of a variable in a name of another variable. Or if there is another, better solution to this problem I have.

Suppose, my code looks like this:

...
 private fun rollDice() {
    // Create new Dice object with 6 sides and roll the dice
    val dice = Dice(6)
    val diceRoll = dice.roll()

    // Find the ImageView in the layout
    val diceImage: ImageView = findViewById(R.id.imageView)

    // Determine which drawable resource ID to use based on the dice roll
    val drawableResource = when (diceRoll) {
        1 -> R.drawable.dice_1
        2 -> R.drawable.dice_2
        3 -> R.drawable.dice_3
        4 -> R.drawable.dice_4
        5 -> R.drawable.dice_5
        else -> R.drawable.dice_6
    }

    // Update the ImageView with the correct drawable resource ID
    diceImage.setImageResource(drawableResource)

    // Update the content description
    diceImage.contentDescription = diceRoll.toString()
}
...

I wonder if in the "Determine which drawable resource ID to use based on the dice roll" block I could actually use something like this (also, sorry, I don't know the correct syntax yet):

val drawableResource = R.drawable.{"dice_"  diceRoll.toString()}

This way I could have saved much space and make the code easily extensible, if, for example, I had a 20-sided dice, I still would have needed this single line of code.

Or else I would have needed to add

when(diceRoll){ 
...
20 lines of code here
...
}

How can I solve this problem? Thank you.

CodePudding user response:

Thanks to Shlomi Katriel for linking the correct solution to this in comment on the original post.

A way to formulate my question in this context would be exactly as in linked post — "How to get a resource id with a known resource name?"

My solution code for this exact case (changed 2 blocks):

// Determine which drawable resource ID to use based on the dice roll
val drawableResourceId : Int = this.resources.getIdentifier("dice_$diceRoll", "drawable",this.packageName)

// Update the ImageView with the correct drawable resource ID
diceImage.setImageResource(drawableResourceId)
  • Related