问题
I tried to compile code that contains
class FixedIndexedRepository(override val name: java.lang.String, location: URI) extends FixedIndexedRepo
Which extends FixedIndexedRepo
which extends Java class AbstractIndexedRepo
public abstract class AbstractIndexedRepo implements RegistryPlugin, Plugin, RemoteRepositoryPlugin, IndexProvider, Repository {
...
protected String name = this.getClass().getName();
...
Unfortunately Scala 2.9.2 compiler stops with an error:
.../FixedIndexedRepository.scala:29: overriding variable name in class AbstractIndexedRepo of type java.lang.String;
[error] value name has incompatible type
[error] class FixedIndexedRepository(override val name: java.lang.String, location: URI) extends FixedIndexedRepo
How to fix this? What is wrong?
回答1:
Rex says it is ugly:
Making a public accessor from an inherited protected Java field
Given:
package j;
public class HasName {
protected String name = "name";
}
then the fake-out is:
package user
private[user] class HasNameAdapter extends j.HasName {
protected def named: String = name
protected def named_=(s: String) { name = s }
}
class User(n: String = "nom") extends HasNameAdapter {
def name(): String = named
def name_=(s: String) { this named_= s }
this name_= n
}
object Test extends App {
val u = new User("bob")
Console println s"user ${u.name()}"
Console println s"user ${u.name}"
}
You were forewarned about the ugly.
I haven't quite worked out the details either, but the weekend is coming up.
Unfortunately Scala 2.9.2 compiler stops with an error
You mean, fortunately it stops with an error.
来源:https://stackoverflow.com/questions/16607517/unable-to-override-java-lang-string-field-what-is-wrong