I would like to construct my domain model using immutable objects only. But I also want to use traits with val fields and move some functionality to traits. Please look at the f
Although you said, you don't want to use case classes. Here is a solution using them:
case class Version(number: Int) {
override def toString = "v" + number
def next = copy(number+1)
}
case class Customer(name: String, version: Version = Version(0)) {
def changeName(newName: String) = copy(newName)
def incrementVersion = copy(version = version.next)
}
Now you can do this:
scala> val customer = new Customer("Scot")
customer: Customer = Customer(Scot,v0)
scala> customer.changeName("McDonnald")
res0: Customer = Customer(McDonnald,v0)
scala> customer.incrementVersion
res1: Customer = Customer(Scot,v1)
scala> customer // not changed (immutable)
res2: Customer = Customer(Scot,v0)