I'd like to get a new instance of some Map with the same content but Map doesn't have a built-in copy method. I can do something like this:

val newInst = someMap.map { it.toPair() }.toMap()

But it looks rather ugly. Is there any more smarter way to do this?

推荐答案

Just use the HashMap constructor:

val original = hashMapOf(1 to "x")
val copy = HashMap(original)

Update for Kotlin 1.1:

Since Kotlin 1.1, the extension functions Map.toMap and Map.toMutableMap create copies.

Kotlin相关问答推荐

在Kotlin中将String转换为T

Kotlin 可空泛型

循环中的每个元素都应填充行中可用的所有可用空间

PRDownloader 即使在实现库后也无法工作.未知参考:Android Studio 中的 PRDownloader

Kotlin 具体类从抽象类和接口扩展而来,接口使用抽象类中实现的方法

is return inside function definition 也是 kotlin 中的表达式

使用 Kotlin 协程时 Room dao 类出错

如何在 kotlin @Parcelize 中使用 null

内联函数导致单元测试代码覆盖率报告出错

IntelliJ 不会根据 ktlint 的期望对 Kotlin 导入进行排序

找不到 androidsdk.modules

面临一些未知问题一些后端jvm内部错误

封闭 lambda 的隐式参数被shadowed

Kotlin:如何修改成对的值?

如何序列化/反序列化Kotlin密封类?

如何限制kotlin协程的最大并发性

可以在函数参数中使用解构吗?

尾随 lambda 语法(Kotlin)的目的是什么?

Java的Kotlin:字段是否可以为空?

如何判断数据是否插入到房间数据库中