Scala | Controlling visibility of constructor fields

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.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.