This second thought seems to be well supported, si...
# getting-started
c
This second thought seems to be well supported, since there is a built-in method that facilitates it: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/to-map.html
r
MutableMap implements the read-only Map interface, so the usual mechanic for this is along the lines of:
Copy code
private val _myMap = mutableMapOf<Int, Int>()
val myMap : Map<Int, Int> = _myMap
so no need to copy everything unless you want to provide a snapshot of the current values instead
2
r
But remember this way all clients will still be able to cast
foo.myMap as MutableMap<Int,Int>
and modify its content.
You could use delegation to protect from casting without copying data:
Copy code
class Foo {
    private val _myMap = mutableMapOf<Int, Int>()
    private class MapWrapper(map: Map<Int,Int>): Map<Int, Int> by map
    val myMap: Map<Int,Int> = MapWrapper(_myMap)
}
c
Neat stuff. Thanks everyone.