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

Kotlin中通过Key获取List对应值遇类型不匹配错误求助

问题解决

问题根源

你当前的Costs变量是通过map生成的**List<List<Any>>类型**,并非键值对结构的Map。List的[]操作符要求传入整数索引,而你传入了字符串"Data A",这就导致了"类型不匹配:推断类型是String但预期是Int"的错误。

修复方案

直接将分组后的结果转换为Map,就能通过键名直接获取对应成本值:

第一步:修改Costs的生成代码

用mapValues替代map,把分组后的列表直接转换为键值对映射:

val costs = Data.groupBy { it.Category }
    .mapValues { (_, value) -> value.sumOf { it.CostInUsd.toBigDecimal() } }

这样costs的类型是Map<String?, BigDecimal>,完美适配你的需求(支持空键的情况,对应输出里的[, 0])。

第二步:正确赋值变量

由于Map的get方法可能返回null(比如键不存在时),需要处理空值情况:

var totalCost: BigDecimal = BigDecimal.ZERO
totalCost = costs["Data A"] ?: BigDecimal.ZERO // 键不存在时用默认值0
println(totalCost)

可选方案(不转Map的情况)

如果一定要保留原List结构,需要遍历List找到对应键的条目:

val dataACost = costs.find { it.firstOrNull() == "Data A" }?.get(1) as? BigDecimal ?: BigDecimal.ZERO
var totalCost: BigDecimal = BigDecimal.ZERO
totalCost = dataACost
println(totalCost)

但这种写法繁琐且效率低,优先推荐转Map的方案。

内容的提问来源于stack exchange,提问作者user18282672

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 08:37:38