Search code examples
kotlindata-structuresmutablemap

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


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

Solution

  • 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 }