Want to update immutable list element in Kotlin? Use the below example to update immutable list element.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | @State(Scope.Thread) open class ModifyingImmutableList { @Param("10", "100", "10000", "1000000") var size: Int = 0 lateinit var players: List<Player> @Setup fun setup() { players = generatePlayers(size) } @Benchmark fun iterative(): List<Player> { return players.mapIndexed { i, player -> if (i == 2) player.copy(score = 100) else player } } @Benchmark fun toMutable(): List<Player> { val updatedPlayer = players[2].copy(score = 100) val mutable = players.toMutableList() mutable.set(2, updatedPlayer) return mutable.toList() } @Benchmark fun toArrayList(): List<Player> { val updatedPlayer = players[2].copy(score = 100) return players.set(2, updatedPlayer) } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.