I have a trait
like this:
trait Identifiable {
def id: Option[Long]
}
and then there are some other case class
es which extend the Identifiable
trait.
for example:
case class EntityA(id: Option[Long], name: String, created: Date) extends Identifiable
case class EntityB(id: Option[Long], price: Long, count: Int) extends Identifiable
assume that I have a Seq[Identifiable]
and I want to assign new id
to each one.
the simplest approach seems to be:
val xs: Seq[Identifiable] = ...
xs.map {
case x: EntityA => x.copy(id = Some(nextId))
case x: EntityB => x.copy(id = Some(nextId))
}
good! but there's is a problem. The more subclasses, The more (duplicate) code to be written.
I tried to get help from Union Types:
xs.map {
case x: EntityA with EntityB => x.copy(id = Some(nextId))
}
or
xs.map {
case x @ (_: EntityA | _: EntityB) => x.copy(id = Some(nextId))
}
but I got an error that says: Cannot resolve symbol copy
Any help would be appreciated. Thanks.