Thursday, August 27, 2009

Beginning Scala - Part 4: val(read-only) and var(read-write)


If we try and do the following, we get an error:
scala> res3 = res3 + 2
:6: error: reassignment to val
res3 = res3 + 2

This is because the entity res3 or for that matter res0, res1 ... resN are all values and not variables. Variables as the name suggests are entities that can vary over a period of time. Values on the other hand, don't! They remain constant, just like a mathematical equation, like x = a + b. Values are like final variables in java. They are immutable. Hence the error. Simply put, val's are read-only entities, whereas var's are read-write. 


This brings us to the first nuance of functional programming, Immutability. In a pure functional programming language all data structures are immutable. Since Scala is both a functional and imperative language, they have provided the additional keyword 'var' which permits mutabilty, and as we'll learn has its place. 

So why is this concept of Immutability there in functional programming?

No comments:

Post a Comment