Skip to content

Scala Reassignment To Val Parameter In Statistics

In Scala, how does one define a local parameter in the primary constructor of a class that is not a data member and that, for example, serves only to initialize a data member in the base class?

For example, in the following code, how could I properly define parameter in the primary constructor of class so that it generates only a temporary local parameter and not a data member?

Randall, your answers explain why the Scala compiler complains when I introduce a method that increments the property , but also change the name of the parameter in the class constructor to match that of the parameter in the class constructor:

Scala compiler output:

Scala complains because class must now have a private, read-only property due to the reference to in . Changing to generates a different compiler error:

Adding doesn't help, either:

How can I use the same name in the parameter in the primary constructor of as the property defined in the primary constructor of the base class ?


Scala allows one to decide whether a variable is immutable or mutable. Immutable is Read only where as mutable is read-write. Immutable variables are declared with the keyword “val“.

scala> val age:Int=22

Here age has been initialized to a value during its declaration. As it has been declared as a val, age cannot be reassigned to a new value. Any attempt to do will result in al reassignment to val error. Let us consider an Array being declared as val.

scala> val names:Array[String]=new Array(6)

Here names reference cannot be changed to point to a different Array, but the array itself can be modified. In other words the contents/elements of the array can be modified.

scala> names= new Array(5) //This will give a reassignment to val error. scala> names(0)="Scala" //This does not give an error.

Also it is to be noted that val variables must be initialized when they are declared.

Mutable variables are delcared with the keyword “var“. Unlike val, “var” can be reassigned to different values or point to different objects. But they have to be initialised at the time of declaration.

scala> var age:Int=22 age: Int=22 scala> age=35 age: Int=35

There’s an exception to the rule that one must initialize the val’s and var’s. When they are used as constructor parameters, the val’s and var’s will be initialised when the object is instantiated. Also, derived classes can override val’s declared inside the parent classes.

Like this: