加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Scala:如何在超类上实现克隆方法,并在子类中使用它?

发布时间:2020-12-16 18:52:29 所属栏目:安全 来源:网络整理
导读:我可能会以错误的方式接近这个,但我希望有一个像这样的对象: class MyDataStructure { def myClone = { val clone = new MyDataStructure // do stuff to make clone the same as this ... clone }}class MyDataStructureExtended(val foo: String) extends
我可能会以错误的方式接近这个,但我希望有一个像这样的对象:

class MyDataStructure {
  def myClone = {
    val clone = new MyDataStructure
    // do stuff to make clone the same as this
    ...
    clone
  }
}

class MyDataStructureExtended(val foo: String) extends MyDataStructure

然后:

val data = MyDataStructureExtended
val dataClone = data.clone
println(dataClone.foo)

所以,问题是dataClone的类型是MyDataStructure,而不是我希望的MyDataStructureExtended.

我想过将类型T添加到超类中,子类可以指定(例如自己),但这似乎不太有希望.

解决方法

假设你想最小化子类中的仪式数量,这是我的建议:

class A extends Cloneable {
  protected[this] def myCloneImpl[T] = {
    val justLikeMe = this.clone
    // copy values and such.
    // Note that the Object.clone method already made a shallow copy,but you may want
    // to deepen the copy or do other operations.
    justLikeMe.asInstanceOf[T]
  }
  def myClone = myCloneImpl[A]
}

class B extends A {
  override def myClone = myCloneImpl[B]
}

通过扩展java.lang.Cloneable并调用Object.clone方法,可以确保运行时类型与要克隆的对象相同.静态类型是使用类型转换(asInstanceOf [T])强制的.您需要覆盖每个子类中的myClone方法并指定类型,但它应该是一个单行.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读