Open In App

Scala | Controlling visibility of constructor fields

Last Updated : 17 Sep, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

The visibility of the Constructor Fields in the Scala language is maintained and controlled by the way of declaration. These can be declared in the below forms:

  • Declared as val
  • Declared as var
  • Declared without var and val
  • Add Private to the fields.

We’ll now see all the above methods with more detail and help of some examples:

When field is declared as var

If the field is declared as var then Scala language automatically generates both Getter and Setter modes for that particular field. This means that the value of the field can always be changed.
Example 1:

When field is declared as val

If the field is declared as val then value of the fields assigned in the start cannot be changed and permanently remains set. In this case Scala only allows getter method.
Example 2:

When field is declared without val and var

If the field is declared without var and val then visibility of the field is very restricted and Scala does not permit setter and getter methods. the visibility of the field becomes restricted.
Example 3:

Adding the keyword Private

We can also mention the keyword “private” in addition with the var and val modes. This makes the field accessibility in the same way as we do in C++. This stops the methods getter and setter and the field is normally accessed using the member functions of the class.

Example 4:

Thus the above-discussed cases are the different kinds of visibility modes that are possible in the Scala Constructor Class.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads