Scala immutable objects and traits with val fields

后端 未结 5 1333
难免孤独
难免孤独 2021-02-08 03:04

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

5条回答
  •  独厮守ぢ
    2021-02-08 03:33

    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)
    

提交回复
热议问题