android - Kotlin:类型推断失败。预期类型不匹配:推断类型为 MutableList<Long?> 但预期为 MutableCollection<Long>

标签 android kotlin collections mutable

我正在尝试使用 kotlin 创建一个 MutableList,但我收到一条错误消息:

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

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

我试过使用:

.toMutableList().toCollection()

但它正在寻找目的地——我不知道该怎么做。

代码 fragment :
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()
    }

任何建议表示赞赏。

最佳答案

问题是可空性,而不是集合类型,即您正在创建 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()

关于android - Kotlin:类型推断失败。预期类型不匹配:推断类型为 MutableList<Long?> 但预期为 MutableCollection<Long>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60859246/

相关文章:

java - 为什么我在 Android Studio 中收到此错误 "Expected resource of type raw"?

android - appcompat v21 抛出 java.lang.UnsupportedOperationException

android - Unresolved reference : kotlinx - Kotlin 1-0-0-rc-1036

kotlin - 即使注销后仍连续运行Gradle-build App(作为服务器守护程序)

java - 如果使用Java 8 Streams列表为空,则返回默认列表?

java - 如何从集合中返回对象。

android - 对话框显示两次

android - 从 Corona Enterprise 插件开发开始

generics - 类型不匹配 : inferred type is List<Any? > 但 List<Nothing> 是预期的

java - 在 Collection<?超T>