kotlinenum-map

Initialize an EnumMap from all of enum's values


I have an enum class:

enum class E { A, B, C, D }

What is the neatest way to initialize an EnumMap containing all of E's values as keys, each with an initial value of 0?

val map = ...?
assert(map is EnumMap<E, Int>)
assert(map[E.A] == 0)
assert(map[E.B] == 0)
assert(map[E.C] == 0)
assert(map[E.D] == 0)

The most concise I could think of is:

val map = E.values().associateWithTo(EnumMap(E::class.java)) { 0 }

However, the repetition of the name E breaks the DRY principle. And the word associateWithTo is a bit of a mouthful. Is there a more concise and readable way? I wish there was something like EnumMap.allOf() just like there is EnumSet.allOf().


Solution

  • The simplest way that I can think of is:

    val map = EnumMap(E.values().associateWith { 0 })