Unable to override java.lang.String field. What is wrong?

孤街醉人 提交于 2019-12-19 03:55:15

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!