Scala: specifying a public method protected method

I am writing trait , which should specify the clone method returning CloneResult , like this:

 trait TraitWithClone extends Cloneable { def clone: CloneResult } 

The goal is to pull the return type of java.lang.Object clone() to something useful for this interface. However, when I try to compile this, I get:

error: clone override method in the View2 attribute of type () CloneResult; the clone method in the Object type () java.lang.Object class has weaker privileges; It must be publicly available. (Note that the clone method in the View2 attribute of type () CloneResult is abstract, and therefore is overridden by the concrete clone method in the Object class of type () java.lang.Object)

How can I require the implementation to be public when Scala does not have a keyword? I know that I can:

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

... but it looks like a hack. Any suggestions?

+7
source share
1 answer

Here's the important part of the error message: "and therefore is overridden by the specific cloning method in the class object."

You must ensure that the clone method is implemented in your statement. This is not ideal, but it is what you need to do, since clone is a concrete method on Object .

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

Although, as a rule, you just do it right in your concrete class:

 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 
+4
source

All Articles