Home > Back-end >  Initialize an EnumMap from all of enum's values
Initialize an EnumMap from all of enum's values

Time:11-26

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().

CodePudding user response:

The simplest way that I can think of is:

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

CodePudding user response:

You can always create your own utility function for this purpose:

fun main() {
    val map = enumMap<E, Int> { 0 }
}

inline fun <reified E : Enum<E>, V> enumMap(valueSelector: (E) -> V): EnumMap<E, V> {
    return enumValues<E>().associateWithTo(EnumMap(E::class.java), valueSelector)
}

CodePudding user response:

val map = EnumMap(EnumSet.allOf(E::class.java).associateWith { 0 })
// {A=0, B=0, C=0, D=0}

Or if you want the map with the 'ordinal' (the position in the enum):

val map = EnumMap(EnumSet.allOf(E::class.java).associateWith(E::ordinal))
// {A=0, B=1, C=2, D=3}

This would be the version for enums with custom properties:

enum class E(val value: String) {
  A("AAA"),
  B("BBB"),
  C("CCC"),
  D("DDD")
}

val map = EnumMap(EnumSet.allOf(E::class.java).associateWith(E::value))
// {A=AAA, B=BBB, C=CCC, D=DDD}
  • Related