First a definition is in order :
“In object-oriented and functional programming, an immutable object (unchangeable object) is an object whose state cannot be modified after it is created. This is in contrast to a mutable object (changeable object), which can be modified after it is created.” dixit wikipedia
So once an immutable variable is created it can not be modified, if we declare a variable lets say
val immutableAcc = 0 immutableAcc = 3
the compiler should show you a nice error.
So Why immutable :
As shown previously immutability contribute to the creation of pure functions, if a variable is immutable, when a function access it and try to modify it, it will create a copy and thus it has full control over it.
But the importance of immutability is way beyond functional programing it serves multiple purposes:
reduce cognitive burden: having dozens of variable can be already hard to keep track of, now imagine all these variables accessed in different places and modified, it becomes a huge mess; our code becomes less readable prone to bugs and less attractive
data sharing optimization: an optimization technique used by some compiler, assigning the same multiple label to the same memory cell. might seem like a negligible thing to do for an INT, but scale it up to bigger data structure
concurrency and race conditions: if you are in the development business a race condition is your worst nightmare, usually it happens when you have a shared ressource (variable, file….) between 2 process running concurrently, one of them is reading the ressource the other is updating it, depending on the order of execution you might get different result on the read.
Now multiple tricks can be set up, like locks or semaphores, but eliminating the shared state using immutable variables, is a clean and safe way to go
keeping a timeline: now using a immutable variables let us draw a timeline in the operations, we can easily track the operation involved in the transformation.
as a user on Quora put it :
“At every moment, the past exists as read-only, immutable chain of events (what has happened has happened), whereas new events (what is happening now) are “appended” at the end of timeline.“