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

Kotlin中String转List<Double>报错问题排查

问题分析与解决方案

核心问题

当前转换逻辑存在两个关键问题:

  • 分割逻辑依赖严格的", "(逗号+空格)作为分隔符,若字符串中存在空格不一致(比如逗号后无空格、多空格),会导致分割出的元素带空格或分割失败,进而触发toDouble()转换异常。
  • toDouble()在遇到无法转换的字符串时会直接抛出NumberFormatException,当前代码未做异常捕获,最终会被Repo层的try-catch捕获,返回错误结果。

修复后的映射器代码

fun ClientEntity.toClientDetails(): ClientDetails {
    return ClientDetails(
        id = id,
        name = name,
        age = age,
        picture = picture,
        aboutUser = aboutUser,
        weight = weight.toListOfDoubles()
    )
}

// 扩展函数更贴合Kotlin风格,同时处理异常和灵活分割
fun String?.toListOfDoubles(): List<Double> {
    if (this.isNullOrBlank()) return emptyList()
    
    // 用正则匹配逗号+任意数量空格,兼容各种分隔格式
    return this.split(",\\s*".toRegex())
        .mapNotNull { it.trim().toDoubleOrNull() } // 转换失败的元素直接过滤
}

额外优化建议

  1. UseCase代码简化:当前UseCase手动创建CoroutineScope并使用suspendCoroutine属于冗余写法,直接在suspend函数内调用Repo即可:
// 优化后的UseCase
suspend operator fun invoke(clientId: Int): Result<ClientDetails> {
    return try {
        clientDetailsRepository.getClientDetailsById(clientId)
    } catch (e: Exception) {
        Result.Error(data = null, errorMessage = e.message ?: "获取客户详情失败")
    }
}
  1. 界面层状态处理:建议使用collectAsState()观察ViewModel中的Flow状态,而非直接取value,确保状态更新能触发界面重组:
// 优化后的界面调用
val viewModel = hiltViewModel<ClientDetailsViewModel>()
clientId?.let { viewModel.loadClientDetails(it) }
val response by viewModel.clientDetailsResponse.collectAsState()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 17:15:16