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
Robert Jaros
04/12/2020, 11:06 PM
But remember this way all clients will still be able to cast
foo.myMap as MutableMap<Int,Int>
and modify its content.
Robert Jaros
04/12/2020, 11:09 PM
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)
}