Scala:指定公共(public)方法覆盖 protected 方法

标签 scala methods overriding clone protected

我正在写 trait应该指定方法clone返回 CloneResult ,这样:

trait TraitWithClone extends Cloneable {
  def clone: CloneResult
}

这里的意图是收紧 java.lang.Object 的返回类型的clone()对这个界面有用的东西。但是,当我尝试编译它时,我得到:

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)



我如何要求实现是 public ,当 Scala 没有关键字时?我知道我可以做到:
trait TraitWithClone extends Cloneable {
  override def clone = cloneImpl
  protected def cloneImpl: CloneResult
}

...但这似乎是一个黑客行为。有什么建议么?

最佳答案

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

您应该提供 clone 的实现你的特质中的方法。这并不理想,但这是您自 clone 以来必须做的事情是 Object 上的具体方法.

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

关于Scala:指定公共(public)方法覆盖 protected 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8618937/

相关文章:

.net - .Net HelloWorld 上的 Scala

scala - 玩!网络服务 : redirect with encoded URL

swift - 试图从扩展类覆盖 NSView 的 drawRect

即使 newValue == oldValue 也会触发更改事件的 JavaFX ObjectProperty

java - android java 如何在嵌套类中覆盖 ParseUser 的 toString

java - 为什么我们需要在 Scala 中为 Double 传递指数形式的数字?

scala - 在Scala中,是否有一种方法可以访问外部作用域中定义的符号(变量)?

c# - this[参数] 语法的用途是什么?

java - 使用在实现中声明但未在接口(interface)中定义的方法

function - 了解 Common Lisp 中的泛型函数?