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.
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.
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.
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.
Thus the above-discussed cases are the different kinds of visibility modes that are possible in the Scala Constructor Class.