'Kotlin I can't add element to the end of the arrayOf
the problem is, that I can't understand differences between:
ARRAY OF
, LIST OF
and ARRAY LIST OF
I know, that arrays are mutable in nature, but list not. When I try to add something at the end of the simple array, there is no function like ADD
and I have to improvise, but is in mutableListOf
but in ListOf
there is no! Why? Lists can change their sizes, and I don't understand why ListOf
doesn't have function like .add
? Can someone explain me in simple words?
Solution 1:[1]
When coming to a language that has functional constructs like Kotlin, one thing to pay attention to is mutability
An immutable object (unchangeable object) is an object whose state cannot be modified after it is created.
Immutable objects are useful because they are inherently thread-safe. Other benefits are that they are simpler to understand and reason about and offer higher security than mutable objects.
To answer your question:
arrayOf()
return anArray
. Kotlin's array elements can be changed so yes you are right, it is mutable. But on the other hand, its size is fixed. That's the reason you cannot invokeadd
on an array.listOf()
return an read-only list, so you cannot suppose to add more elements into it or change its element.arrayListOf()
return anArrayList
which is an implementation of mutable list. You can add more elements to this list, remove elements as well as change its element.
UPDATE 2/12/2020
Thank you for pointing it out, Alex.T. I need to correct one thing. listOf()
doesn't return an immutable list, actually it returns a read-only list.
A read-only list is almost the same as an immutable list. It prevents being modified; however, if the underlying list is modified, the read-only list is changed too. You can modify the underlying list by casting it to mutable, or change it from Java.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |