Better way to set all the keys to map to false in a mutable map

1k views Asked by At

I have a mutable map

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
)

How do I set all the keys to false. Currently I am using something like this, is there a better way to do this.

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)
}
2

There are 2 answers

2
Sweeper On BEST ANSWER

You can use replaceAll - ignore the given key and value, and just return false no matter what. This will replace everything with false.

weeklyCheck.replaceAll { _, _ -> false }
0
A-run On

This can be used to achieve same results:

Days.values().forEach { weekFilter[it] = false }