https://kotlinlang.org logo
Title
c

Chris Cordero

04/12/2020, 10:36 PM
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

rbares

04/12/2020, 10:40 PM
MutableMap implements the read-only Map interface, so the usual mechanic for this is along the lines of:
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.
You could use delegation to protect from casting without copying data:
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

Chris Cordero

04/13/2020, 12:12 AM
Neat stuff. Thanks everyone.