Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin and Immutable Collections?

Tags:

kotlin

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?

like image 935
tmn Avatar asked Nov 16 '15 02:11

tmn


People also ask

What is Kotlin mutable collection?

Mutable collections and their corresponding methods are: List – mutableListOf(),arrayListOf() and ArrayList. Set – mutableSetOf(), hashSetOf() Map – mutableMapOf(), hashMapOf() and HashMap.

What does immutable mean in Kotlin?

What does Immutable mean? By definition, immutable means that, once created, an object/variable can't be changed. So, instead of changing a property of an object, you have to make a copy (or clone) of the entire object and in the process, change the property in question.

What are Kotlin collections?

Collections in Kotlin are used to store group of related objects in a single unit. By using collection, we can store, retrieve manipulate and aggregate data.


Video Answer


1 Answers

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.

like image 197
nhaarman Avatar answered Sep 22 '22 13:09

nhaarman