Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
805 views
in Technique[技术] by (71.8m points)

kotlin - How to turn a Mutable Collection into an Immutable one

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 user, but to avoid any unsafe publication of my data I wanted to expose it in immutable collections even when internally being handled by mutable ones.

class School {

    val roster: MutableMap<Int, MutableList<String>> = mutableMapOf<Int, MutableList<String>>()

    fun add(name: String, grade: Int): Unit {
        val students = roster.getOrPut(grade) { mutableListOf() }
        if (!students.contains(name)) {
            students.add(name)
        }
    }

    fun sort(): Map<Int, List<String>> {
        return db().mapValues { entry -> entry.value.sorted() }
                .toSortedMap()
    }

    fun grade(grade: Int) = db().getOrElse(grade, { listOf() })
    fun db(): Map<Int, List<String>> = roster //Uh oh!
}

I managed to expose only Map and List (which are immutable) in the public API of my class, but the instances I am actually exposing are still inherently mutable.

Which means an API user could simply cast my returned map as an ImmutableMap and gain access to the precious private data internal to my class, which was intended to be protected of this kind of access.

I couldn't find a copy constructor in the collection factory methods mutableMapOf() or mutableListOf() and so I was wondering what is the best and most efficient way to turn a mutable collection into an immutable one.

Any advice or recommendations?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use Collections to converts a Mutable list to Immutable list, Example:

Mutable list:

val mutableList = mutableListOf<String>()

Converts to Immutable list:

val immutableList = Collections.unmodifiableList(mutableList)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...