Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between MutableList and List in Kotlin

Tags:

kotlin

  1. What is the difference between MutableList and List in Kotlin?
  2. and what is the use of each type?
like image 335
Deepan Avatar asked Sep 27 '17 10:09

Deepan


People also ask

What is the difference between ArrayList and MutableList in Kotlin?

ArrayList is a class that happens to implement the MutableList interface. The only difference is that arrayListOf() returns the ArrayList as an actual ArrayList. mutableListOf() returns a MutableList, so the actual ArrayList is "disguised" as just the parts that are described by the MutableList interface.

What is MutableList in Kotlin?

A Mutable List is an interface and generic collection of elements. Once a collection is declared as mutable, it becomes dynamic and we can modify its data as per requirement. A mutable list grows automatically in size as we insert new elements into it. The Mutable List inherits form the Generic<T> class.

What is the difference between mutable and immutable list in Kotlin?

Types of ImmutabilityMutable – The contents of the list can be freely changed. Read-Only – The contents of the collection are not meant to be changed. However, the underlying data can be changed. Immutable – Nothing can change the contents of the collection.

How do I add a list to Kotlin MutableList?

To add an element to a Mutable List in Kotlin, we can use add(element), or add(index, element) functions. add(element) adds element to the end of this Mutable List. add(index, element) adds element to this Mutable List at the given index.


1 Answers

From docs:

List: A generic ordered collection of elements. Methods in this interface support only read-only access to the list; read/write access is supported through the MutableList interface.

MutableList: A generic ordered collection of elements that supports adding and removing elements.

You can modify a MutableList: change, remove, add... its elements. In a List you can only read them.

like image 90
Miguel Isla Avatar answered Oct 05 '22 07:10

Miguel Isla