I would like to define an extension of the enum class
which accepts a list of values in the same order as the enum constants and outputs an EnumMap
.
What I've been able to do instead is create and extension of the List<V>
object with an array of the keys from Enum<K>.values()
as input.
It seems the difficulty is enum class
is not itself a object having a .values()
method. So perhaps my request is not sensible.
Here is a working example using the list extension method.
import java.util.*
enum class Shoes(
val title: String,
val weight: Double) {
WORKBOOT("tough", 11.0),
SNEAKER("fast", 6.0),
SLIPPER("soft", 3.0);
}
fun main(args: Array<String>) {
val prices= listOf(11.5,8.2,3.5)
val map = prices.enumMapOf(Shoes.values())
map.print()
}
inline fun <reified K : Enum<K>, V> List<V>.enumMapOf(keys:Array<K>): EnumMap<K, V> {
val map = EnumMap<K, V>(K::class.java)
keys.forEachIndexed{i,k-> map[k]=this[i]}
return map
}
fun <K:Enum<K>,V> EnumMap<K,V>.print() {
this.forEach{k,v-> println("%d: %s --> %.2f".format(k.ordinal,k.name,v)) }
}