Scala. The difference between var and val

This is one of the first questions when starting to learn Scala. There seems to be two types of variables. Why? The reason is actually quite brilliant and even though I have worked in a dozen of other languages I have not seen it before. The reason is the we as programmers often make constant variables. This is in itself a contradiction so in Scala they are simply called Values, or Val so once it is set it cannot be changed:

Here you can see I define a value to be speed of light. This is something I probably will not change in the duration of my program so I will make it a val. If I try to change it the compiler will complain.

If this was a regular variable I would be allowed to change the value and perhaps mess up an important calculation:

Maybe I meant speed of flight (shrug). Anyway now it is all f’ed up.

Other languages have the same idea but I cannot remember seeing it as clearly separated as in Scala.

We usually say the var is mutable and val is immutable but I prefer variable and value or constant. Why put a bow on it?


Posted

in

by

Tags: