gpt4 book ai didi

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

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

我试图编译包含的代码

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

如何解决这个问题?怎么了?

最佳答案

雷克斯说它很丑:

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

你被预先警告过丑陋。

我也没有完全弄清楚细节,但周末快到了。

Unfortunately Scala 2.9.2 compiler stops with an error



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

关于scala - 无法覆盖 java.lang.String 字段。怎么了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16607517/

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