【问题标题】:Kotlin: Type inference failed. Expected type mismatch: inferred type is MutableList<Long?> but MutableCollection<Long> was expectedKotlin:类型推断失败。预期类型不匹配:推断类型为 MutableList<Long?> 但预期为 MutableCollection<Long>
【发布时间】:2020-07-06 14:42:42
【问题描述】:

我正在尝试使用 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】:

    问题在于可空性,而不是集合类型,即您正在创建一个 List&lt;Long?&gt;,而应该是 List&lt;Long&gt;

    您可以通过以下方式重现您的错误消息 (inferred type is MutableList&lt;Long?&gt; but MutableCollection&lt;Long&gt; was expected):

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

    您可以通过插入.filterNotNull() 来修复它以删除潜在的空值,并将List&lt;T?&gt; 转换为List&lt;T&gt;

    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()
    

    【讨论】:

    • 解决了我的问题,谢谢
    猜你喜欢
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-23
    • 1970-01-01
    相关资源
    最近更新 更多