How to make immutable variable in scala
To make an immutable variable in Scala, you can use the val
keyword. Here's an example:
val myVariable: Int = 42
In this example, myVariable
is declared as an immutable variable of type Int
and assigned the value 42
. Once assigned, the value of myVariable
cannot be changed.
You can also omit the explicit type declaration and let Scala infer the type for you, like this:
val myVariable = 42
In this case, Scala will infer that myVariable
is of type Int
based on the assigned value.
Immutable variables are useful because they provide safety and help prevent accidental modifications to the variable's value.