我想获得一些具有相同内容的Map的新实例,但Map没有内置copy
方法.我可以这样做:
val newInst = someMap.map { it.toPair() }.toMap()
Run Code Online (Sandbox Code Playgroud)
但它看起来相当难看.还有更聪明的方法吗?
Ing*_*gel 53
只需使用HashMap
构造函数:
val original = hashMapOf(1 to "x")
val copy = HashMap(original)
Run Code Online (Sandbox Code Playgroud)
Kotlin 1.1更新:
自Kotlin 1.1起,扩展功能Map.toMap
和Map.toMutableMap
创建副本.
使用putAll
方法:
val map = mapOf("1" to 1, "2" to 2)
val copy = hashMapOf<String, Int>()
copy.putAll(map)
Run Code Online (Sandbox Code Playgroud)
要么:
val map = mapOf("1" to 1, "2" to 2)
val copy = map + mapOf<String, Int>() // preset
Run Code Online (Sandbox Code Playgroud)
你的方式对我来说也很惯用.
归档时间: |
|
查看次数: |
11878 次 |
最近记录: |