Suppose I have the following scala classes ( that needs to improve to address the concern
in this question and may not be valid scala classes):
@Entity
class Hotel extends Model {
private var name: String = _;
private var stars: Int = _;
@Embedded
private var address: Address = _;
def someMethod() = {
// do something
}
}
class Address {
private var street: String = _;
private var city: String = _;
private var postCodet: String = _;
}
In groovy I can do this in single like:
def hotel = new Hotel(name: "some Hotel", stars: 5, address: new Address(street: "342 main", city: "edmond", postCode: "12345"))
Does Scala have something like that and how can I improve the class declarations shown above to improve the design. Note that I must have those annotations that comes from another Java library. Also once a class is instantiated or otherwise obtained from a database, I must be able to modify individual fields ( mutable).
Address can be defined as:
This assumes you want the variables to be modifiable later.
You can than create an Address with
Hotel is a little more interesting because of the need for an annotation. I think this will do the trick for you:
EDIT: Fixed @Embedded
If it doesn’t, you may have to resort to something like:
Note, if the variables on the object are not modifiable, you can use val rather than var on the class definition. This way, something like address.street will return the current value of street, but address.street = “new street address” will not compile.