gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:36:01 25 4
gpt4 key购买 nike

我正在写 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com