提问人:user13125638 提问时间:3/26/2020 最后编辑:user13125638 更新时间:3/26/2020 访问量:17348
Kotlin:类型推断失败。预期类型不匹配:推断类型为 MutableList<Long?>但 MutableCollection<Long> 是预期的
Kotlin: Type inference failed. Expected type mismatch: inferred type is MutableList<Long?> but MutableCollection<Long> was expected
问:
我正在尝试使用 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()
}
任何建议都是值得赞赏的。
答:
10赞
Erik Vesteraas
3/26/2020
#1
问题在于可空性,而不是集合类型,即您正在创建一个预期 a 的地方。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()
您可以通过插入以删除潜在的空值来修复它,并将 a 转换为 :.filterNotNull()
List<T?>
List<T>
val foo: MutableCollection<Long> =
listOf(1L, 2, 3, 4, null)
.filterNotNull()
.toMutableList()
(所以你的电话实际上是不需要的,可以挂断).toCollection()
特定于代码的其他一些说明:
你可能想用 over ,并且可以组合成 ,所以总而言之,你可能想把你的链写成.values
.elements.toList()
map { }.filterNotNull()
mapNotNull
hashMapHrm.values
.filter { it.isIn }
.sortedByDescending { it.adjustRssi }
.mapNotNull { it.serialNumber }
.toMutableList()
评论