Anyone have a good way to add properties to a map on the toMap() call?
Often I have to create a mutable map, that I then add the properties to and then make immutable.
Would it be sensible to add something like this to the language? (or does something like it exist?)
public fun <K, V> Iterable<Pair<K, V>>.toMap(vararg pairs: Pair<K, V>): Map<K, V> {
if (this is Collection) {
if (pairs.isEmpty()) {
return this.toMap()
}
return when (size + pairs.size) {
1 -> { pairs.toMap() }
else -> {
val map = toMap(LinkedHashMap(mapCapacity(size + pairs.size)))
map.putAll(pairs)
map.toMap()
}
}
}
val map = toMap(LinkedHashMap(mapCapacity(pairs.size)))
map.putAll(pairs)
return toMap(map).optimizeReadOnlyMap()
}
Example usage
val collection = mapOf("k1" to "v1")
val result = collection.map { it.key to it.value }.toMap("example" to "extra")
// "k1": "v1"
// "example": "extra"