scala – 密封特征/对象案例类字节代码从2.9.1更改.到2.9.2?

两个目录中的源文件相同

我在Errors.scala中有以下密封特征,我想在Java类中引用它.在Scala 2.9.1中,我能够从Java引用Errors.TooBig作为错误$TooBig $在2.9.2中不再编译.

Errors.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 $class文件的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 $’的类.

最佳答案 您不应该依赖类名来从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();
点赞