我正在写一个小游戏,其中一部分是跟踪玩家的分数。为此,我将地图初始化如下:
// given: players: List<Player>
var scores: MutableMap<Player, Int> = mutableMapOf(*players.map { it to 0 }.toTypedArray())
让我感到困扰的是,我需要在.toTypedArray()
的结果上使用map { it to 0 }
才能应用展开运算符*
。有办法避免这种情况吗?通过压缩两个数组创建地图时也会出现同样的问题:
// does not compile:
mapOf(*a1.zip(a2))
// works but more verbose:
mapOf(*a1.zip(a2).toTypedArray())
答案 0 :(得分:6)
val pointsByPlayer = players.map { it to 0 }.toMap(mutableMapOf())
那就是说,更好的设计可能只是在Player类中有一个可变的points
属性。
答案 1 :(得分:2)
gestureRecognizer(_:shouldReceive:)
功能也有助于解决您的问题,看起来更好imho:
associate
拉链更容易:
val scores: MutableMap<Player, Int> = players.associate { it to 0 }.toMutableMap()