Scala:指定公共方法覆盖受保护方法

发布于 2024-12-22 22:18:12 字数 767 浏览 2 评论 0原文

我正在编写一个 trait ,它应该指定返回 CloneResult 的方法 clone ,如下所示:

trait TraitWithClone extends Cloneable {
  def clone: CloneResult
}

这里的目的是收紧返回类型java.lang.Objectclone() 到对此接口有用的东西。但是,当我尝试编译它时,我得到:

错误:重写 ()CloneResult 类型特征 View2 中的克隆方法; ()java.lang.Object类型的类Object中的方法clone具有较弱的访问权限;它应该是公开的; (请注意, ()CloneResult 类型的特质 View2 中的方法 clone 是抽象的, 因此被类型为 ()java.lang.Object) 的类 Object 中的具体方法 clone 覆盖

当 Scala 没有关键字时,如何要求实现是 public ?我知道我可以这样做:

trait TraitWithClone extends Cloneable {
  override def clone = cloneImpl
  protected def cloneImpl: CloneResult
}

……但这似乎是一种黑客行为。有什么建议吗?

I'm writing a trait that should specify the method clone returning a CloneResult, as so:

trait TraitWithClone extends Cloneable {
  def clone: CloneResult
}

The intention here is to tighten up the return type of java.lang.Object's clone() to something useful to this interface. However, when I try to compile this, I get:

error: overriding method clone in trait View2 of type ()CloneResult;
method clone in class Object of type ()java.lang.Object has weaker access privileges; it should be public;
(Note that method clone in trait View2 of type ()CloneResult is abstract,
and is therefore overridden by concrete method clone in class Object of type ()java.lang.Object)

How can I require that an implementation be public, when Scala doesn't have the keyword? I know I can do:

trait TraitWithClone extends Cloneable {
  override def clone = cloneImpl
  protected def cloneImpl: CloneResult
}

...but that seems like a hack. Any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

樱花细雨 2024-12-29 22:18:12

这是错误消息的重要部分:“因此被对象类中的具体方法克隆覆盖”。

您应该在您的特征中提供 clone 方法的实现。这并不理想,但这是您必须做的,因为 cloneObject 上的具体方法。

trait TraitWithClone extends Cloneable {
  override def clone: CloneResult = throw new CloneNotSupportedException
}

虽然,通常你只是直接在你的具体类中做这种事情:

class Foo extends Cloneable {
  override def clone: Foo = super.clone.asInstanceOf[Foo]
}

scala> new Foo
res0: Foo = Foo@28cc5c6c

scala> res2.clone
res1: Foo = Foo@7ca9bd

Here's the important part of the error message: "and is therefore overridden by concrete method clone in class Object".

You should provide an implementation of the clone method in your trait. It's not ideal, but it's what you have to do since clone is a concrete method on Object.

trait TraitWithClone extends Cloneable {
  override def clone: CloneResult = throw new CloneNotSupportedException
}

Although, usually you just do this sort of thing in your concrete class directly:

class Foo extends Cloneable {
  override def clone: Foo = super.clone.asInstanceOf[Foo]
}

scala> new Foo
res0: Foo = Foo@28cc5c6c

scala> res2.clone
res1: Foo = Foo@7ca9bd
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文