0

So I've come to learn that the it in my foreach loop is immutable - namely I get the error val cannot be reassigned.

results.forEach{
            val subGenreNames = subGenreNames(it.subGenres)
            it.subGenres = subGenreNames
}

However I want to be able to update its value after I pass it into my subGenreNames function.

How can I achieve this?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
userMod2
  • 8,312
  • 13
  • 63
  • 115

2 Answers2

0

Are you sure you want to mutate subGenres rather than create new list with updated values? The more Kotlin way would be

val withSubGenreNames = results.map {
            it.copy(subGenres = subGenreNames(it.subGenres))
}

where copy is magical method if your it is data class.

This way you'd keep old list unchanged. You can read here why immutability is generally a good practice.

Evgeny Bovykin
  • 2,572
  • 2
  • 14
  • 27
0

Your quation was answered in the comments by @Egor, so I will just post the answer for you to resolve:

The it in the labda is immutable but the actual setter accesses inner field subGenres, which I guess is a val. Change subGenres to a var.

Neo
  • 1,869
  • 1
  • 7
  • 20