How to turn a Mutable Collection into an Immutable one

后端 未结 6 1026
醉话见心
醉话见心 2020-12-14 14:52

I was writing a small piece of code in which I internally handle my data in a mutable map, which in turn has mutable lists.

I wanted to expose my data to the API use

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-14 15:33

    A classic solution is to copy your data, so that even if modified, the change would not affect the private class property:

    class School {
        private val roster = mutableMapOf>()
    
        fun db(): Map> = roster.mapValuestTo {it.value.toList}
    }
    

提交回复
热议问题