Scala immutable objects and traits with val fields

后端 未结 5 1335
难免孤独
难免孤独 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:15

    Here's another solution that, like the OP's code, doesn't work. However, it may provide a simpler (and more generally useful) starting point for extending the language.

    trait Versionable[T] {
       self: { def copy(version: Int): T } =>
       val version = 0
       def incrementVersion = copy(version = version + 1)
    }
    
    case class Customer(name: String, override val version: Int) 
          extends Versionable[Customer] {
       def changeName(newName: String) = copy(name = newName)
    }
    

    The code would work if the compiler recognized the Customer class's copy method as conforming to the method defined in Versionable's self-type annotation, which seems like a natural way to use named and default parameters.

提交回复
热议问题