问题描述:

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:

class Address(var street:String, var city: String, var postCodet: String)

This assumes you want the variables to be modifiable later.

You can than create an Address with

new Address(street="street", city="city", postCodet="a1a1a1")

Hotel is a little more interesting because of the need for an annotation. I think this will do the trick for you:

class Hotel(var name:String, var stars:Int, @Embedded var address: Address) extends Model {
       def someMethod() = {...}
}

EDIT: Fixed @Embedded

If it doesn't, you may have to resort to something like:

class Hotel(var name:String, var stars:Int, address_in: Address) extends Model {
@Embedded
var address:Address = address_in

...
}

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.

相关阅读:
Top