I am writing a small game, and part of that is to keep track of player's scores. For this, I have a map initialized as follows:
// given: players: List<Player>
var scores: MutableMap<Player, Int> = mutableMapOf(*players.map { it to 0 }.toTypedArray())
What bothers me is that i need to use .toTypedArray()
on the result of the map { it to 0 }
before I can apply the spread operator *
. Is there a way to avoid this? The same problem also occurs when creating a map by zipping two arrays:
// does not compile:
mapOf(*a1.zip(a2))
// works but more verbose:
mapOf(*a1.zip(a2).toTypedArray())
Kotlin Map : mapOf() Kotlin distinguishes between immutable and mutable maps. Immutable maps created with mapOf() means these are read-only and mutable maps created with mutableMapOf() means we can perform read and write both. The first value of the pair is the key and the second is the value of the corresponding key.
Kotlin MutableMap is an interface of collection frameworks which contains objects in the form of keys and values. It allows the user to efficiently retrieve the values corresponding to each key. The key and values can be of the different pairs like <Int, String>, < Char, String>, etc.
val pointsByPlayer = players.map { it to 0 }.toMap(mutableMapOf())
That said, a better design would probably to simply have a mutable points
property in the Player class.
The associate
function can also help with solving your problem and looks even better imho:
val scores: MutableMap<Player, Int> = players.associate { it to 0 }.toMutableMap()
And the zipping is even easier:
val zipped = a1.zip(a2).toMap()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With