为具有许多案例类的类层次结构定义通用副本 [英] Define common copy for a class hierarchy with many case classes

查看:89
本文介绍了为具有许多案例类的类层次结构定义通用副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想定义一个类层次结构,其中包含约100个案例类,它们是从公共基础派生的。这些类型描述了AST层次结构中的节点,例如这一个。我想按照以下方式做些事情:

I would like to define a class hierarchy with about 100 case classes deriving from common base. The types are describing nodes in the AST hierarchy, like this one. I would like to do something along the lines of:

trait Base {
  def doCopy: Base
}

trait CloneSelf[T <: CloneSelf[T]] extends Base {
  self: T =>

  def copy(): T
  override def doCopy: T = copy()
}


case class CaseA(a: String) extends Base with CloneSelf[CaseA]

case class CaseB(b: Int) extends Base with CloneSelf[CaseB]

这会产生错误,因为我的副本的存在会阻止 case类定义自动副本。有什么方法可以实现克隆 doCopy ,以便使用那些<$ c的自动副本 $ c>案例类?

This gives an error, because the existence of my copy prevents the case classes from defining the automatic copy. Is there some way how to implement the "clone" doCopy so that is uses the automatic copy of those case classes?

推荐答案

我发现定义了实际上,每个 case类中的doCopy 比定义每个要从 CloneSelf 继承的类的工作量要少。 。代码如下所示:

I have found out defining the doCopy in each case class is actually less work than defining each class to inherit from CloneSelf. The code looks like this:

trait Base {
  def doCopy: Base
}

case class CaseA(a: String) extends Base {
  def doCopy = copy()
}

case class CaseB(b: Int) extends Base {
  def doCopy = copy()
}

我很惊讶地发现没有重写方法上的显式类型,该类型是由编译器推断的,因此 CaseA( a)。doCopy 的静态类型与 CaseA( a)。copy(),即 CaseA ,而不是 Base 。为每个 case类添加显式类型可能会更明显,但这与将同一行复制粘贴到每个行中相比需要更多的工作。并不是很重要-当我通过 case class 类型进行复制时,我可以使用 copy()作为好。只有当我拥有 Base 时,我才需要 doCopy ,因此将其声明为 def doCopy:Base = copy()不会造成太大危害。

I was surprised to learn that without explicit type on the overridden method the type is inferred by the compiler, therefore the static type of CaseA("a").doCopy is the same as of CaseA("a").copy(), i.e. CaseA, not Base. Adding explicit type for each case class would be probably more obvious, but this would require more work compared to just copy-pasting the same line into each of them. Not that it matters much - when I do copying via the case class type, I may use the copy() as well. It is only when I have the Base I need the doCopy, therefore declaring it like def doCopy: Base = copy() would do little harm.

这篇关于为具有许多案例类的类层次结构定义通用副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆