4

两个目录中的相同源文件

我想在 Java 类中引用 Errors.scala 中的以下密封特征。在 Scala 2.9.1 中,我能够将 Java 中的 Errors.TooBig 引用为 Errors$TooBig$,它在 2.9.2 中不再编译。

错误.scala

package com.abc

sealed trait Error

object Errors {
  case object TooBig extends Error
}

JavaTest.java

import com.abc.Errors$TooBig$;
public class JavaTest {
}

我在两个不同的目录(2.9.1/2.9.2)中有相同的源文件。我可以使用 2.9.1 编译源代码,但不能使用 2.9.2。

>2.9.1$ brew switch scala 2.9.1
>2.9.1$ scalac Errors.scala
>2.9.1$ javac -classpath .:/usr/local/Cellar/scala/2.9.1/libexec/lib/scala-library.jar JavaTest.java
>2.9.1$
>2.9.1$ cd ../2.9.2
>2.9.2$ brew switch scala 2.9.2
>2.9.2$ scalac Errors.scala
>2.9.2$ javac -classpath .:/usr/local/Cellar/scala/2.9.2/libexec/lib/scala-library.jar JavaTest.java
JavaTest.java:1: cannot find symbol
symbol  : class Errors$TooBig$
location: package com.abc
import com.abc.Errors$TooBig$;
              ^
1 error
}
}

这是 com.abc.Errors$TooBig$ 类文件的 javap 转储的差异:

mhughes:~/scalatest$ diff 2.9.1/TooBig.txt 2.9.2/TooBig.txt 
2c2
< public final class com.abc.Errors$TooBig$ extends java.lang.Object implements com.abc.Error,scala.ScalaObject,scala.Product,scala.Serializable
---
> public final class com.abc.Errors$TooBig$ extends java.lang.Object implements com.abc.Error,scala.Product,scala.Serializable
5a6,7
>   InnerClass: 
>    public final #68= #9 of #67; //TooBig$=class com/abc/Errors$TooBig$ of class com/abc/Errors
73,80c75,84
< const #65 = Asciz com/abc/Error;
< const #66 = class #65;    //  com/abc/Error
< const #67 = Asciz scala/ScalaObject;
< const #68 = class #67;    //  scala/ScalaObject
< const #69 = Asciz scala/Product;
< const #70 = class #69;    //  scala/Product
< const #71 = Asciz scala/Serializable;
< const #72 = class #71;    //  scala/Serializable
---
> const #65 = Asciz InnerClasses;
> const #66 = Asciz com/abc/Errors;
> const #67 = class #66;    //  com/abc/Errors
> const #68 = Asciz TooBig$;
> const #69 = Asciz com/abc/Error;
> const #70 = class #69;    //  com/abc/Error
> const #71 = Asciz scala/Product;
> const #72 = class #71;    //  scala/Product
> const #73 = Asciz scala/Serializable;
> const #74 = class #73;    //  scala/Serializable

您可以清楚地看到 2.9.1 和 2.9.2 都生成了一个名为 'Errors$TooBig$' 的类。

4

1 回答 1

2

您不应该依赖类名来从 Java 中检索 scala 对象。您可以编写一个旨在从 Java 调用的静态工厂:

package com.abc

sealed trait Error

object Errors {
  case object TooBig extends Error

  //Java API
  def getTooBig(): Error = TooBig
}

然后,从 Java 调用它:

import com.abc.*;

Error tooBig = Errors.getTooBig();
于 2012-06-14T17:20:20.187 回答