Kotlin - An Elegant Way to Expose a Mutable List as an Immutable List

Viewed 373

I have a class where I want to be able to modify a list internally, but externally I want the list to be immutable; for example...

class Foo {
    val items: List<String> get() = mutableItems
    private val mutableItems: MutableList<String> = mutableListOf()
}

Is there a nicer way to express this?

2 Answers

You can do something like this:

private val items : MutableList<String> = mutableListOf()
fun items() : List<String> = items

When you want to access your items externally just use items() function. In internal usage work with list directly

Related