Scala A random instance of the parent instance instance class when calling copy ()

I use case classes for models in ORM. Each model has an identifier, but the identifier should not be publicly available. So I have a parent trait

trait WithId {
  private var id: Long = 0
}

and many classes of cases (models) inheriting from it

case class C1(a: Int, b: String) extends WithId
case class C2(...) extends WithId
...

Now, if someone calls copy () in the case class, he does not copy the identifier with him, but sets it to 0.

val c1 = C1(3, "bla")
//Set c1.id to a value != 0
val c2 = c1.copy(b="bla2")
//c1.id !=0, but c2.id = 0

I want it to also copy the id.

Since I have many such classes, I would prefer to have as little code as possible in class classes. Thus, the implementation of the copy () method in each case will have a lot of template code.

- , copy() ? , - ? , ?

id ,

case class C1(a: Int, b: String, protected var id: Long)

. , case, , id case, case. , .

+3
1

, , ID:

class IdToken private[myPackage] (val id: Int) {
  override def equals(a: Any) = a match {
    case tok: IdToken => id == tok.id
    case _ => false
  }
  override def hashCode = id.hashCode ^ 0x157135
  override def toString = ""
}
object IdToken {
  private var lastId = 0
  private[myPackage] def next = { lastId += 1; new IdToken(lastId) }
}

, , , .

trait WithID { protected def idToken: IdToken }

case class C1(a: Int, b: String, protected val idToken: IdToken = IdToken.next) extends WithID {
  def checkId = idToken.id
}

( checkId ),

scala> C1(5, "fish")
res1: C1 = C1(5,fish,)

scala> res1.copy(a = 3)
res2: C1 = C1(3,fish,)

scala> res1.checkId == res2.checkId
res3: Boolean = true

, val - protected.

, .

+1

All Articles