roman
roman

Reputation: 33

call different variables with the same prefix changing only suffix

I have 20 variables (it may be 20 different mutableList items, or it may be a 20 buttons or any other objects), for example:

var ex1 
var ex2 
var ex3 
...
var ex20 

And i need to make a for loop, which will look like this:

for (i in 0 until 20) {
//here i want to do something with variable that i have declared earlier
i+1
}

so, how can i go throught all the variables?

Upvotes: 1

Views: 161

Answers (2)

Vishnu Vijaykumar
Vishnu Vijaykumar

Reputation: 450

Create an array var[] ex and insert all the twenty var elements to that array. Iterate the array inside the for loop to access the 20 var elements

Upvotes: 1

D. Karchnak
D. Karchnak

Reputation: 101

It's not really possible, you should really take a look into using arrays for this kind of behavior.

val array = arrayOf(5, 32, 555, 921)

//To get numbers in array
for(num in array) {
    //Do something
}

//To change numbers in array
for(i in 0 until array.size) {
    array[i] = 2
}

Upvotes: 0

Related Questions