有没有更惯用的方式在Kotlin初始化这张地图?

blu*_*ubb 5 dictionary initialization kotlin

我正在写一个小游戏,其中一部分是跟踪玩家的分数.为此,我将地图初始化如下:

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

困扰我的是我需要使用.toTypedArray()map { it to 0 }之前的结果才能应用扩展运算符*.有办法避免这种情况吗?通过压缩两个数组创建映射时也会出现同样的问题:

// does not compile:
mapOf(*a1.zip(a2))

// works but more verbose:
mapOf(*a1.zip(a2).toTypedArray())
Run Code Online (Sandbox Code Playgroud)

JB *_*zet 6

val pointsByPlayer = players.map { it to 0 }.toMap(mutableMapOf())
Run Code Online (Sandbox Code Playgroud)

也就是说,更好的设计可能只是points在Player类中具有可变属性.


s1m*_*nw1 2

该associate函数还可以帮助解决您的问题,并且看起来更好:

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

压缩更容易:

val zipped = a1.zip(a2).toMap()
Run Code Online (Sandbox Code Playgroud)