Reputation: 13
fun Sample(){
val x = 10
x = 11 // will give error as it cannot be reassigned
val arr = arrayOf(1,2,3)
arr[0] = 5 // will not give any error but why ? aren't they supposed to be final?
}
Why val doesn't works for arrays?
Upvotes: 1
Views: 349
Reputation: 19534
val
s aren't really immutable data, it's better to think of them as read-only references. You can change the value of a var
, but you can't change the thing a val
points at. But that doesn't mean the thing itself can't change!
If the object itself is mutable, or has mutable var
properties, or has val
properties that point to other mutable things... you get the idea. You can't guarantee absolute immutable state, it's just not baked into the language (or Java itself - final
just means you can't reassign the variable!)
That's why Kotlin has a bunch of features to try and help you avoid mutable state, or at least to prevent you from changing things. Collection
s (and the return types of the functions that operate on them) are usually immutable by default, and you have to explicitly ask for a mutableList
or whatever. That's enforcing immutability by stopping you from accessing methods like add
and remove
, but it still doesn't stop you from putting mutable objects in there!
data class
es are another tool, and that's sort of aimed at a more functional, data-driven approach. The idea is that ideally, you'll just put val
s in them, and any non-primitive data types you use will also comprise of val
s - so when you drill down, everything ends in immutable variables, so the whole thing is immutable overall. Things like the copy
method allow you to "change" the data without actually mutating it, similar to a Copy On Write approach.
I'd also say that in my experience, it's not uncommon for arrays specifically to always be treated as a mutable type, though. Like there's no immutable version of an array in Kotlin, and things like F# (which encourages functional transformations on its types) explicitly has setters on its Array
types. So if you need a read-only array... use a List
!
Upvotes: 0
Reputation: 10330
arr
itself is immutable and can't be reassigned....the contents of array are not. For example you could not do:
val arr1 = arrayOf(1,2,3)
val arr2 = arrayOf(4,5,6)
arr1 = arr2 // error
An alternative if you want a "read-only" list is to use listOf()
Upvotes: 2
Reputation: 1647
By declaring and array as with val, you basically declare the reassigning for the array isn't possible, but array items are still reassignable
Upvotes: 1