Kotlin and Immutable Collections?

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.

Parameters
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.

Parameters
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.

Leave a Comment