在可变映射中将所有键设置为 false 的更好方法

ARU*_*NGH 0 data-structures kotlin mutablemap

我有一个可变的地图

val weeklyCheck = mutableMapOf(
    Day.MONDAY to true,
    Day.TUESDAY to true,
    Day.WEDNESDAY to true,
    Day.THURSDAY to true,
    Day.FRIDAY to true,
    Day.SATURDAY to true,
    Day.SUNDAY to true
)
Run Code Online (Sandbox Code Playgroud)

如何将所有键设置为 false。目前我正在使用这样的东西,有没有更好的方法来做到这一点。

private fun resetDays() {
    weeklyCheck.put(Days.MONDAY, false)
    weeklyCheck.put(Days.TUESDAY, false)
    weeklyCheck.put(Days.WEDNESDAY, false)
    weeklyCheck.put(Days.THURDSAY, false)
    weeklyCheck.put(Days.FRIDAY, false)
    weeklyCheck.put(Days.SATURDAY, false)
    weeklyCheck.put(Days.SUNDAY, false)
}
Run Code Online (Sandbox Code Playgroud)

Swe*_*per 6

您可以使用replaceAll- 忽略给定的键和值,false无论如何都返回。这将用false.

weeklyCheck.replaceAll { _, _ -> false }
Run Code Online (Sandbox Code Playgroud)

  • 这就是“replaceAll”所做的......@ARUNSINGH (4认同)