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

为何调用toMutableList()后仍出现MutableList与List类型不匹配错误?

问题原因分析

你的代码里虽然调用了toMutableList(),但后续的distinct()和reversed()方法会将可变列表转换为只读List,这就是为什么最终返回类型被识别为List<String>而非MutableList<String>。

具体来看每个方法的返回类型:

  • toMutableList():返回MutableList<String>,这一步没问题
  • distinct():标准库中该方法的返回类型是List<T>(只读列表),调用后会丢失可变性
  • reversed():同样返回List<T>,进一步保持了只读特性

所以整个链式调用的最终结果类型是List<String>,和方法要求的MutableList<String>不匹配,就出现了类型错误。

解决方案

你可以在链式调用的最后再调用一次toMutableList(),把只读列表转回可变列表:

return (stringToArray(userSharedPrefs.getString(MY_KEY, null))?.toMutableList()?.distinct()?.reversed()?.toMutableList() ?: mutableListOf<String>())

或者调整顺序,先执行去重和反转操作,再转成可变列表(效果相同,但逻辑更清晰):

return (stringToArray(userSharedPrefs.getString(MY_KEY, null))?.distinct()?.reversed()?.toMutableList() ?: mutableListOf<String>())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 09:30:26