val mutableList vs var immutableList. When to use which in Kotlin?

Technology CommunityCategory: Kotlinval mutableList vs var immutableList. When to use which in Kotlin?
VietMX Staff asked 3 years ago

Mutable and immutable list increase the design clarity of the model.
This is to force developer to think and clarify the purpose of collection.

  1. If the collection will change as part of design, use mutable collection
  2. If model is meant only for viewing, use immutable list

Purpose of val and var is different from immutable and mutable list.
val and var keyword talk about the how a value/reference of a variable should be treated.

  • var – value/reference assigned to a variable can be changed at any point of time.
  • val – value/reference can be assigned only once to a variable and can’t be changed later point in the execution.

There are several reasons why immutable objects are often preferable:

  • They encourage functional programming, where state is not mutated, but passed on to the next function which creates a new state based on it. This is very well visible in the Kotlin collection methods such as map, filter, reduce, etc.
  • A program without side effects is often easier to understand and debug (you can be sure that the value of an object will always be the one at its definition).
  • In multithreaded programs, immutable resources cannot cause race conditions, as no write access is involved.

You have also some disadvantages:

  • Copying entire collections just to add/remove a single element is computationally expensive.
  • In some cases, immutability can make the code more complex, when you tediously need to change single fields. In Kotlin, data classes come with a built-in copy() method where you can copy an instance, while providing new values for only some of the fields.