Holm
Holm

Reputation: 3365

Increase all elements in MutableList by 1 the Kotlin way

I have a list

val result = MutableList(N) { 0 }

I want to increase 1 for elements in the list result

this works

for (item in result.withIndex()) {
                result[item.index] = result[item.index] + 1
}

but is there more kotlin way of doing it? like it-> it+=1 ? I got val cannot be reassigned using this

Upvotes: 1

Views: 599

Answers (1)

Alexey Soshin
Alexey Soshin

Reputation: 17721

"Kotlin way" would be not to mutate lists at all, but to produce a new list instead using something like .map{ it + 1 }

But if you do want to use mutableList for some reason, replaceAll is a valid option:

result.replaceAll { it + 1 }

Upvotes: 7

Related Questions