You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:09:27