Newbie question: MutableList or var property

Hi Guys,

I am requesting your opinion. I can have a class like for example
class MyClass<T>(val myList: List<T>)

If I want to make myList modifiable I could take two approaches:

  1. Make myList a MutableList and then I can add or remove from the list
  2. Make myList a var property and then just reassign a new object when needed

Which approach do you consider better and why (for example less error-prone)?
Or there is not truly a best solution and it depends on the use case?

Thanks for your attention

It depends. I would say in 99 of 100 cases you would want to use a MutableList if you want to modify it as this would clearly indicate what is supposed to happen. You want to modify the list.

There might be some special case where you have multiple immutable lists and your list variable points to the active list. In that case you want to use var so you can change out the entire list. In that case you can still not modify the list directly. You can only create a modified copy and assign it.

A third option, which I sometimes use is this:

class MyClass<T> (list: List<T>){
   private val _list = list.toMutableList()
   public val list: List<T>
      get() = _list.toList()

This way you can modify the list in the class, but it looks like a immutable List to the outside. However, everyone can just cast it back to a mutableList, so there is no guarantee someone outside of the class can not change it. In that case you would need to return a copy of the list.

1 Like

My favorite answer :smile: That means I have to think twice before setting a var parameter.

It took me some time to understand what you did there, hehe. I can’t imagine how messy it would look with several properties defined like this, but I do get the point.

So I will be using mutable lists for the cases when I really need to modify it.

Thanks for your answer

Yeah. I try too keep it to a minimum. But in some rare cases it is advantages to internally use a mutable list without giving someone on the outside the option of modifying it. (Normally only when some other state is directly linked to the list and you have to ensure the other state is updated when the list is changed. And yes, it is better to avoid situations like this. Sadly not always possible)

1 Like