'Insert Image using variable name in Kotlin [duplicate]

I currently am working on an app that has a list of characters and images associated with each of them.

I want to insert images for all the characters using a for loop without actually hardcoding their image names:

Example:

var agentsList = listOf(
        "Astra",
        "Breach",
        "Brimstone",
        "Chamber",
        "Cypher",
        "Jett",
        "KAY/O",
        "Killjoy",
        "Neon",
        "Omen",
        "Phoenix",
        "Raze",
        "Reyna",
        "Sage",
        "Skye",
        "Sova",
        "Viper",
        "Yoru"
    )
for (agent in agentsList) {
    dataList.add(DataModel(agent, R.drawable.agent)
}

Here , R.drawable.agent is where I want to insert the images , but i want the for loop to do it for me using the string resource in agentsList.

I have saved the image using the same strings as the characters in agentsList, so that won't be an issue.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source