Home > Software engineering >  Kotlin, is there a nice and simple way to ommit the val problem?
Kotlin, is there a nice and simple way to ommit the val problem?

Time:09-30

I've been just wondering if there is a way to ommit the Val cannot be reassigned error when accessing every element of a list and trying to execute some action on it. For example:

for (number in numbers) {
    if (number%2==0){
        number *= 2
    }
}

or

numbers.forEach {
    if (it%2==0){
        it *= 2
    }
}

causes such an error. I know, i could do it like:

for (i in numbers.indices){
    if (numbers[i]%2==0){
        numbers[i] *= 2
    }
}

But I wonder if there's a better way to do it.

CodePudding user response:

There isn't a way to change the variable in such range based loops. Iterating over indices is the only way.

Although for your particular case, you can use the map function,

numbers.map { if(it % 2 == 0) 2 * it else it

Note that the map function returns a new list without modifying the original list so you will have to use the return value for further usage.

CodePudding user response:

You could create a helper function like this. I don't think there's something like this in the standard library for mutating each element of a MutableList:

inline fun <T> MutableList<T>.transformEach(transform: (T)->T) {
    for (i in indices) {
        this[i] = transform(this[i])
    }
}

Then the code for your example could be converted to:

numbers.transformEach { if (it % 2 == 0) it * 2 else it }
  • Related