45
  1. What is the difference between MutableList and List in Kotlin?
  2. and what is the use of each type?
Herry
  • 7,037
  • 7
  • 50
  • 80
Deepan
  • 787
  • 2
  • 7
  • 13
  • You may take a look at the answers [here](https://stackoverflow.com/questions/33727657/kotlin-and-immutable-collections). – BakaWaii Sep 27 '17 at 10:58
  • 1
    Possible duplicate of [Kotlin and Immutable Collections?](https://stackoverflow.com/questions/33727657/kotlin-and-immutable-collections) – Abhishek Aryan Sep 27 '17 at 11:46

2 Answers2

71

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.

Miguel Isla
  • 1,379
  • 14
  • 25
25

SUMMARY: List is read-only while MutableList allows you to add, edit and remove items

  • List

     var language: List<String> = listOf("java", "kotlin", "dart")
    

List type is an interface which provides read-only access. you are limited to read operations like

get, indexof, subList, contains, size etc

with kotlin you have access to some more functions **like sort, stream,binarySearch

  • MutableList

Consider this example:

    var mutableLanguage: MutableList<String> = mutableListOf("java", "kotlin", "dart")
    

with mutablelist you can perform read and write operation i.e., add or remove contents of a list. beside supporting all the functions of interface type List.

add, addAll, replace, replaceAll, set, removeAt etc

Extremis II
  • 5,185
  • 2
  • 19
  • 29