Kotlin 中 listOfDoubles 的字符串错误

问题描述 投票:0回答:1

我想将字符串中的 ClientEntity.weight 解析为 ClientDetails.weight,这是双打列表,并在我的屏幕中使用它。

我的映射器:

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

fun toListOfDoubles(weight: String?): List<Double>? {
    return weight?.split(", ")?.map { it.toDouble() } ?: emptyList()
}

在我看来模特:

 val result = getClientDetailsUseCase.invoke(clientId)

用例:

suspend operator fun invoke(clientId: Int) : Result<ClientDetails> = suspendCoroutine { continuation ->
    val coroutineScope = CoroutineScope(Dispatchers.IO)
    coroutineScope.launch {
        val result = clientDetailsRepository.getClientDetailsById(clientId)
        continuation.resume(result)
    }
}

RepoImpl:

  override suspend fun getClientDetailsById(clientId: Int): Result<ClientDetails> {
        return try {
            val response = clientDao.getClientsDetailsById(clientId)
                .toClientDetails()

            Result.Success(data = response, errorMessage = "Client details")
        } catch (e: Exception) {
            Result.Error(data = null, errorMessage = e.message ?: "Problem")
        }
    }

我的屏幕视图模型调用:

val viewModel = hiltViewModel<ClientDetailsViewModel>()
    val data = clientId?.let { viewModel.getClientDetailsById(clientId = it) }
    val response = viewModel.clientDetailsResponse.value

在我的 ClientDetailsScreen 中出现错误:对于输入字符串“1.1、2.2、3.3”

编辑:

通过 chatGPT 我得到了这个:

在创建 ClientDetails 对象之前,您在 toClientDetails() 函数中使用此函数将 ClientEntity 对象的权重值转换为双精度列表。

android kotlin android-room kotlin-coroutines use-case
1个回答
1
投票

您确定导致问题的输入字符串正是您将其粘贴到此处的方式,空格和所有内容?将字符串解析为双精度列表似乎是一个问题。如果您首先删除所有空格然后用单个逗号分隔或使用正则表达式匹配逗号后的所有潜在空格,那么可能会更不容易出错,例如:

weight?.split(",\\s*".toRegex())?.map { it.toDoubleOrNull() }?.filterNotNull() ?: emptyList()
.

即使它不能解决问题,尽可能多地清理输入字符串仍然是件好事。

© www.soinside.com 2019 - 2024. All rights reserved.