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

使用Kotlin any操作符检查购物车列表时遇类型转换异常如何解决?

解决ClassCastException:FurnitureModel无法转为CartModel的问题

问题根源

报错的核心是从SharedPreferences读取的列表实际是FurnitureModel类型的集合,但你强制转换成了ArrayList<CartModel>,导致类型转换失败。这说明你之前往SharedPreferences里存储的是FurnitureModel列表,而非CartModel列表。

解决方案

1. 修正读取逻辑,兼容旧数据

如果需要保留之前存储的FurnitureModel数据,先按正确类型读取,再转换为CartModel列表:

// 先按原类型读取旧数据
val oldFurnitureList: ArrayList<FurnitureModel>? = generalFunctions.getSharedPreferencesArray(ApplicationConstants.UTILS.sharedPreferencesCartKey)
val cartList: ArrayList<CartModel> = if (oldFurnitureList != null) {
    // 将旧的FurnitureModel转为CartModel,默认数量设为1
    oldFurnitureList.map { CartModel(it, 1) } as ArrayList<CartModel>
} else {
    ArrayList()
}
// 执行判断逻辑
val hasFurnitureAdded = cartList.any { it.furniture == furniture }

2. 确保后续存储的是CartModel列表

检查你往SharedPreferences存数据的代码,确保存储的是CartModel类型的集合,而非FurnitureModel:

// 示例存储代码
generalFunctions.saveSharedPreferencesArray(
    ApplicationConstants.UTILS.sharedPreferencesCartKey,
    cartList // 此处必须传入ArrayList<CartModel>类型的对象
)

3. (可选)直接清理旧数据(无需兼容时)

如果不需要保留之前的旧数据,可以直接清除对应SharedPreferences键值,之后重新初始化正确的CartModel列表:

// 清除旧数据
generalFunctions.getSharedPreferences().edit()
    .remove(ApplicationConstants.UTILS.sharedPreferencesCartKey)
    .apply()
// 初始化空购物车列表
val cartList = ArrayList<CartModel>()

额外注意点

  • FurnitureModel是data class,默认的equals方法会比较所有属性,因此it.furniture == furniture的判断逻辑是有效的,只要两个FurnitureModel的所有属性值一致就会返回true。
  • 若只需按家具名称判断是否存在,可修改判断条件为it.furniture.furnitureName == furniture.furnitureName,避免因其他属性差异导致判断失误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 15:17:13