我想把Map<DAO, Int>号 map 换成Map<String, Boolean>号 map ,但我不能把 map 还给你. map 功能中的条目:

itemsWithQuantity.mapTo(mutableMapOf<String, Boolean>(), { it.key.toString() to it.value != 0 })

(当然我使用的是更复杂的映射函数,但没关系,问题是一样的)

上面写着

MutableMap<String, Boolean> is not a subtype of MutableCollection<Pair<String, Boolean>>.

So how can I return Map.Entry instead of Pair?

现在我这样做:

val detailsIds = mutableMapOf<String, Boolean>()
itemsWithQuantity.forEach { item, quantity -> detailsIds.put(it.key.toString(), it.value != 0) }

但是我想用mapTo

推荐答案

Use associateTo instead:

xs.associateTo(mutableMapOf<String, Boolean>(), { "${it.key}" to (it.value != 0) })

Also, note the brackets around it.value != 0.

map类似,mapTo函数不会将结果收集到Map中,而是与Collection一起使用,希望您提供MutableCollection<Pair<String, Boolean>>.

Kotlin相关问答推荐

在没有外部 map 的情况下转换列表项

只能在元素区域中点击的Jetpack Compose列

可选的.在kotlin中不使用泛型参数

在Spring Boot应用程序中使用网络请求功能将关键字挂起作为冗余

如何在 kotlin 中的数据类中为变量提供多种类型

generic 类实例列表 - 调用采用 T 的函数

Kotlin 可空泛型

为什么记得不将 StateFlow 转换为特定类型?

使用事务时未调用 Kafka ConsumerInterceptor onCommit

将 SharedPreferences 中的值公开为流

listOf() 返回 MutableList

无法从 XML 访问 NavHostFragment

Android Kotlin StringRes 数量String

将 Android Studio 升级到 3.1.0 后的 Android Support 插件错误

RecyclerView SnapHelper无法显示第一个/最后一个元素

添加抽象的私有getter和公共setter的正确方法是什么?

Java Integer.MAX_VALUE 与 Kotlin Int.MAX_VALUE

spring.config.location 在 Spring Boot 2.0.0 M6 上不起作用

Kotlin-将UTC转换为当地时间

Android:Exoplayer - ExtractorMediaSource 已弃用