Scala trait 可以复制它的子类吗?

Can a Scala trait copy its subclass?

我想制作一个可以产生其子副本的特征class。 subclass 保证是 case class,所以应该有一个 copy 方法。我在这里做错了什么?

trait Copyable[C <: Copyable[C] with Product] {

  def specialCopy: C =
    this.asInstanceOf[C].copy() // doesn't compile

}

The subclass is guaranteed to be a case class

不,不是。 Product 可以通过非大小写实现 类.

即使是,copy 不同情况下的方法 类 也是具有不同签名的不同方法,没有单一的 copy 方法可以调用。

虽然您可以主要使用反射和productIterator实现specialCopy。大约:

 def specialCopy = getClass.getConstructors()(0).newInstance(this.asInstanceOf[Product].productIterator.asInstanceOf[Iterator[Object]].toSeq: _*)

这不适用于具有多个参数列表(包括隐式参数)的 类 或内部 类。