Kotlin:类型推断失败。预期类型不匹配:推断的类型为MutableList ,但MutableCollection 预期

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

我正在尝试使用kotlin创建MutableList,但出现错误提示:

类型推断失败。预期的类型不匹配:推断的类型为MutableList,但预期为MutableCollection]

...而且我不确定如何将MutableList转换为MutableCollection。

我尝试使用:

.toMutableList().toCollection()

但是它正在寻找目的地-我不确定该怎么办。

代码段:

data class HrmSearchResult(
    var rssi: Short?,
    var adjustRssi: Short?,
    var timeout: Int,
    var serialNumber: Long?,
    var isIn: Boolean,
    var countIn: Int
)

private val hashMapHrm = ConcurrentHashMap<Long?, HrmSearchResult>()

val hrmDeviceList: MutableCollection<Long>
    get() = try {
        if (hashMapHrm.elements().toList().none { it.isIn}) {
            //if there are no member in range, then return empty list
            arrayListOf()
        } else {
            hashMapHrm.elements()
                .toList()
                .filter { it.isIn }
                .sortedByDescending { it.adjustRssi }
                .map { it.serialNumber }
                .toMutableList().toCollection()
        }
    } catch (ex: Exception) {
        AppLog.e(
            LOG, "Problem when get devices " +
                    "return empty list: ${ex.localizedMessage}"
        )
        arrayListOf()
    }

任何建议都值得赞赏。

android kotlin collections mutable
1个回答
1
投票

问题是可为空性,而不是集合类型,即您正在创建List<Long?>且期望为List<Long>的情况。

您可以使用此方法最小程度地重现错误消息(inferred type is MutableList<Long?> but MutableCollection<Long> was expected):

val foo: MutableCollection<Long> =
    listOf(1L, 2, 3, 4, null)
        .toMutableList()

并且您可以通过插入.filterNotNull()除去潜在的空值并将List<T?>转换为List<T>来解决此问题:

val foo: MutableCollection<Long> =
    listOf(1L, 2, 3, 4, null)
        .filterNotNull()
        .toMutableList()

(因此您实际上不需要.toCollection()通话,可以将其挂断)

一些其他特定于您代码的注释:

[您可能想在.values上使用.elements.toList(),并且map { }.filterNotNull()可以合并为mapNotNull,因此,总之,您可能希望将链写为]

hashMapHrm.values
    .filter { it.isIn }
    .sortedByDescending { it.adjustRssi }
    .mapNotNull { it.serialNumber }
    .toMutableList()
© www.soinside.com 2019 - 2024. All rights reserved.