Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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())
like image 825
blubb Avatar asked Mar 11 '18 13:03

blubb


People also ask

Is map immutable in Kotlin?

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.

Is Kotlin map mutable?

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.


2 Answers

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.

like image 64
JB Nizet Avatar answered Sep 23 '22 22:09

JB Nizet


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()
like image 25
s1m0nw1 Avatar answered Sep 20 '22 22:09

s1m0nw1