1
votes

I'm reading Kotlin docs. At Immutability sector, they comment below. I wonder why should we do that? When I tried the example code, it acts the same.

Immutability

Prefer using immutable data to mutable. Always declare local variables and properties as val rather than var if they are not modified after initialization.

Always use immutable collection interfaces ( Collection , List , Set , Map ) to declare collections which are not mutated. When using factory functions to create collection instances, always use functions that return immutable collection types when possible:

// Bad: use of mutable collection type for value which will not be mutated
fun validateValue(actualValue: String, allowedValues: HashSet<String>) { ... }
// Good: immutable collection type used instead
fun validateValue(actualValue: String, allowedValues: Set<String>) { ... }
// Bad: arrayListOf() returns ArrayList<T>, which is a mutable collection type
val allowedValues = arrayListOf("a", "b", "c")
// Good: listOf() returns List<T>
val allowedValues = listOf("a", "b", "c")

Updated: For anyone who voted me down. I read this book, tried the example and tried to search before writing this question. So I don't have enough experience to explain or comprehend the paragraph above. Let consider what you contribute to this community. If I do wrong, let me know. Don't click only one button.

1
Why do you want to use mutable if you are not planning on changing the data structure? If anything having the data structure immutable will prevent you or others from changing it by accident.Akavall
Sorry but I don't want to use mutable. Maybe I don't understand ArrayList<T> and List<T> in Kotlin. In Java, List<T> just be an Interface. Therefore, I can't understand that suggests.Trần Đức Tâm
List<T> is an interface in Kotlin as well.chris
Oh, so this problem stands for the difference between arrayListOf and listOf . Let me read the API Docs again. Thank u for your help.Trần Đức Tâm
I think you should compare MutableList<T> and List<T>. Both are interfaces, whereas ArrayList<T> is a concrete class from Java. ArrayList<T> implements MutableList<T> in Kotlin. MutableList<T> extends List<T>, adding mutability functionalities which are not in List<T> originally.Naetmul

1 Answers

2
votes

As the suggestion of Mr.@Akavall and Mr.@Naetmul. I read the listOf method's docs again. The problem has I missed that the listOf method returns a list object that can't add any new item.

I think you should compare MutableList and List. Both are interfaces, whereas ArrayList is a concrete class from Java. ArrayList implements MutableList in Kotlin. MutableList extends List, adding mutability functionalities which are not in List originally.