Scala-Java不兼容,在类中引用与静态内部类同名的静态字段



取这个Java类:

public class Fisk {
    public static class A {
    }
    public static A A = new A();
}

这个Java代码工作:

    Fisk.A a = new Fisk.A();
    Fisk.A b = Fisk.A;

但是从Scala调用它:

    val fisk = new Fisk.A()
    val strupp = Fisk.A

导致编译器错误:

error: ambiguous reference to overloaded definition,
[INFO] both variable A in object Fisk of type Fisk.A
[INFO] and  object A in object Fisk of type object Fisk.A
[INFO] match expected type ?
[INFO]          val strupp = Fisk.A
[INFO]                                   ^
[ERROR] one error found

有谁知道解决这个问题的方法,或者我必须重命名我的静态字段吗?

——Andreas

scala> Fisk.A
<console>:8: error: ambiguous reference to overloaded definition,
both variable A in object Fisk of type Fisk.A
and  object A in object Fisk of type object Fisk.A
match expected type ?
       Fisk.A
            ^
// this is the static field A of Fisk
scala> Fisk.A: Fisk.A
res1: Fisk.A = Fisk$A@d86c58
// this is a new constructed instance of type Fisk.A
scala> val fisk = new Fisk.A()
fisk: Fisk.A = Fisk$A@462f90
// this is the static field A of Fisk (see the same hashcode)
scala> val strupp: Fisk.A = Fisk.A
strupp: Fisk.A = Fisk$A@d86c58

这里有一个解释和一个解决方案。

最新更新