Scala uses the val keyword to define values.
Sample code to define a value looks as below.
val x : Int = 3
val is designed to store immutable values, and the compiler would protect you from inadvertently changing the current value.
For example, reassignment to val error is thrown when a value is re-assigned.
val x : Int = 3x = 4 //reassignment to val
In the above example, the type of x is specified to be of type Int, but this is not necessary. Compiler would try to infer the type of the value based on the statement.
val x = 3
So, whenever you need to define values that you do not want changed, you you should think of the “val” keyword. Always, use “val” so that you are protected from any future code that might attempt to change the val.
Additionally, state change adds a lot of complexity to your program. So, you might want to minimize state changes except when you do not have a choice. So declare all your values using the “val” keyword as opposed to using the “var” keyword, which would allow you to change the value.
Variables would be used when you need to have “side effects”, and need to change the state of a variable.
var x = 3
x = 4
println(x)
Variables are mutable while values are immutable.