How to access and change the name of a private field in scala?

I have something like:

class Address(private var street:String, private var city: String, private var postCode: String) extends Model 

When I try to do:

 address = new Address(....) address.city = "changed" 

I get a compilation error. So what is the solution? Please note that the fields must remain closed.

There is also a shortcut syntax than repeating the private keyword when all the fields in the class are private?

+6
source share
2 answers

Here, there seems to be a fundamental misunderstanding. All fields in Scala are private. This is not only the default, but also optional.

For example, let's say you have this:

 class Address(var street: String) 

The field in which street is stored is closed. Say you do it:

 val x = new Address("Downing") println(x.street) 

This code does not have direct access to the private field for street . x.street is a getter method.

Say you do it:

 x.street = "Boulevard" 

This code does not directly change the private field for street . x.street = is actually the x.street_= method, which is the setter method.

You cannot directly access fields in Scala. Everything is done through getters and setters. In Scala, each field is private, each field has getters, and each var has setters.

+18
source

You can define accessors and mutators like this:

 class Address(private var _street: String, private var _city: String, private var _postCode: String){ def street = _street def street_=(street: String) = _street = street def city = _city def city_=(city: String) = _city = city def postCode = _postCode def postCode_=(postCode: String) = _postCode = postCode } 

It is necessary to rename the fields (which may encounter named parameters) and that the constructor ignores the mutator when the class instance is a known problem, but no attempt is currently made to improve the situation.

+5
source

Source: https://habr.com/ru/post/891488/


All Articles