我有两个类PixelObject
,ImageRefObject
还有更多,但这里只是这两个类来简化事情。它们都是trait Object
包含 uid 的 a 的子类。我需要通用方法,它将使用给定的 new 复制案例类实例uid
。我需要它的原因是因为我的任务是创建一个类 ObjectRepository ,它将保存任何子类的实例Object
并用 new 返回它uid
。我的尝试:
trait Object {
val uid: Option[String]
}
trait UidBuilder[A <: Object] {
def withUid(uid: String): A = {
this match {
case x: PixelObject => x.copy(uid = Some(uid))
case x: ImageRefObject => x.copy(uid = Some(uid))
}
}
}
case class PixelObject(uid: Option[String], targetUrl: String) extends Object with UidBuilder[PixelObject]
case class ImageRefObject(uid: Option[String], targetUrl: String, imageUrl: String) extends Object with UidBuilder[ImageRefObject]
val pix = PixelObject(Some("oldUid"), "http://example.com")
val newPix = pix.withUid("newUid")
println(newPix.toString)
但我收到以下错误:
➜ ~ scala /tmp/1.scala
/tmp/1.scala:9: error: type mismatch;
found : this.PixelObject
required: A
case x: PixelObject => x.copy(uid = Some(uid))
^
/tmp/1.scala:10: error: type mismatch;
found : this.ImageRefObject
required: A
case x: ImageRefObject => x.copy(uid = Some(uid))
^
two errors found