无法覆盖java.lang.String字段。怎么了?

时间:2013-05-17 11:08:28

标签: scala scala-2.9

我尝试编译包含

的代码
class FixedIndexedRepository(override val name: java.lang.String, location: URI) extends FixedIndexedRepo

扩展了FixedIndexedRepo扩展了Java类AbstractIndexedRepo

public abstract class AbstractIndexedRepo implements RegistryPlugin, Plugin, RemoteRepositoryPlugin, IndexProvider, Repository {
...
protected String name = this.getClass().getName();
...

不幸的是,Scala 2.9.2编译器因错误而停止:

.../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

如何解决这个问题?有什么问题?

1 个答案:

答案 0 :(得分:1)

雷克斯说这很难看:

Making a public accessor from an inherited protected Java field

假设:

package j;

public class HasName {
    protected String name = "name";
}

那么假装是:

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}"
}

你被预先警告了丑陋。

我还没有详细说明细节,但周末即将来临。

  

不幸的是,Scala 2.9.2编译器因错误而停止

你的意思是,幸运的是它会因错误而停止。