Kotlin技术问询:EnumMap初始化与转普通Map简化方法
问题2:是否有更简洁的方式将EnumMap转换为普通Map?
Definitely! You can ditch the manual for-loop entirely with Kotlin’s built-in collection functions. The best fit here is mapKeys(), which transforms the original map’s keys while preserving their associated values—exactly what you need to convert enum keys to their string names:
fun doLog(enumParamMap: EnumMap<RegisteredKey, String>) { val stringKeyMap = enumParamMap.mapKeys { it.key.name } api.log(stringKeyMap) }
If your api.log() method specifically requires a mutable map (though most APIs accept read-only Map), just chain toMutableMap():
val mutableStringKeyMap = enumParamMap.mapKeys { it.key.name }.toMutableMap()
Another equivalent option is using associate() on the map entries, which achieves the same result with slightly different syntax:
val stringKeyMap = enumParamMap.entries.associate { it.key.name to it.value }
Both functions are far more concise than writing a loop, and they’re idiomatic Kotlin that other developers will instantly understand.
内容的提问来源于stack exchange,提问作者lannyf

