Updated Wed, 13 Jul 2022 18:52:27 GMT

Kotlin and Immutable Collections?

I am learning Kotlin and it is looking likely I may want to use it as my primary language within the next year. However, I keep getting conflicting research that Kotlin does or does not have immutable collections and I'm trying to figure out if I need to use Google Guava.

Can someone please give me some guidance on this? Does it by default use Immutable collections? What operators return mutable or immutable collections? If not, are there plans to implement them?


Kotlin's List from the standard library is readonly:

interface List<out E> : Collection<E> (source)

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.

E - the type of elements contained in the list.

As mentioned, there is also the MutableList

interface MutableList<E> : List<E>, MutableCollection<E> (source)

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

E - the type of elements contained in the list.

Due to this, Kotlin enforces readonly behaviour through its interfaces, instead of throwing Exceptions on runtime like default Java implementations do.

Likewise, there is a MutableCollection, MutableIterable, MutableIterator, MutableListIterator, MutableMap, and MutableSet, see the stdlib documentation.

Comments (3)

  • +1 – Interesting approach although it makes sense to ensure interoperability. I may stick with Guava collections because (the last time I checked) the performance is much better. — Nov 16, 2015 at 15:36  
  • +4 – Kotlin collections are readonly, not immutable @nhaarman. I suggested an edit to your answer. — Dec 27, 2015 at 00:57  
  • +1 – Note that if you create a list using arrayListOf() the list returned is an ArrayList, which is mutable. If you want an immutable list you must use listOf() instead. — Aug 30, 2017 at 05:06