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.
ArrayList<T>
andList<T>
in Kotlin. In Java,List<T>
just be anInterface
. Therefore, I can't understand that suggests. – Trần Đức TâmList<T>
is an interface in Kotlin as well. – chrisarrayListOf
andlistOf
. Let me read the API Docs again. Thank u for your help. – Trần Đức TâmMutableList<T>
andList<T>
. Both are interfaces, whereasArrayList<T>
is a concrete class from Java.ArrayList<T>
implementsMutableList<T>
in Kotlin.MutableList<T>
extendsList<T>
, adding mutability functionalities which are not inList<T>
originally. – Naetmul