Var + mutable lists vs val and immutable lists

Is there general advice if it is better to use var and immutable lists or val and mutable lists if a collection needs to be modified?

The concrete use case is: Storing listener references which can be added and removed.

(there is a similar question on Stackoverflow which I’m summarizing here)

Both approaches have different pros and cons. A mutable list in a val is usually more efficient, if you are modifying it often. An immutable list in a var on the other hand is safer, if it is accessible to the outside of your class/method, or you ever pass or return it somewhere else: with a mutable list, the outside code could modify the list. The consensus from Stackoverflow answers is, to use a var with an immutable list always is the safe choice.

So for your use case, handling a list of listeners, I’d assume that it isn’t changed often enough to be performance-critical and I’d use a var with an immutable list.


Thank you for your reply!

I had equal considerations: The collection of listeners won’t be changed so often that this could lead to a performance issue; and if the list is accidantly exposed to the outside it is still immutable and safe.