Scala:指定公共方法覆盖受保护方法
我正在编写一个 trait
,它应该指定返回 CloneResult
的方法 clone
,如下所示:
trait TraitWithClone extends Cloneable {
def clone: CloneResult
}
这里的目的是收紧返回类型java.lang.Object
的 clone()
到对此接口有用的东西。但是,当我尝试编译它时,我得到:
错误:重写 ()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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是错误消息的重要部分:“因此被对象类中的具体方法克隆覆盖”。
您应该在您的特征中提供
clone
方法的实现。这并不理想,但这是您必须做的,因为clone
是Object
上的具体方法。虽然,通常你只是直接在你的具体类中做这种事情:
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 sinceclone
is a concrete method onObject
.Although, usually you just do this sort of thing in your concrete class directly: