我正在尝试使用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()
}
任何建议都值得赞赏。
答案 0 :(得分:3)
问题是可为空性,而不是集合类型,即您正在创建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()