Is there a more idiomatic way to initialize this map in Kotlin?

I am writing a small game, and part of this is to track player ratings. For this, I have a card initialized as follows:

// given: players: List<Player> var scores: MutableMap<Player, Int> = mutableMapOf(*players.map { it to 0 }.toTypedArray()) 

My concern is that I need to use .toTypedArray() for the result of map { it to 0 } before I can apply the spread operator * . Is there any way to avoid this? The same problem occurs when creating a map by fastening two arrays:

 // does not compile: mapOf(*a1.zip(a2)) // works but more verbose: mapOf(*a1.zip(a2).toTypedArray()) 
+5
source share
2 answers

The associate function can also help in solving your problem and looks even better imho:

 val scores: MutableMap<Player, Int> = players.associate { it to 0 }.toMutableMap() 

And the clasp is even simpler:

 val zipped = a1.zip(a2).toMap() 
+2
source
 val pointsByPlayer = players.map { it to 0 }.toMap(mutableMapOf()) 

However, a better design should probably just have the mutable points property in the Player class.

+6
source

Source: https://habr.com/ru/post/1275829/


All Articles