从java访问scala对象字段

时间:2011-10-17 00:37:56

标签: java scala interop

我无法从java访问scala对象的字段。

Scala的:

object TestObject {
  val field = 5 
}

爪哇:

public class JavaTest
{
  public static void main(String[] args)
  {
    int i = TestObject.field;
  }
}

错误:

[error] JavaTest.java: cannot find symbol
[error] symbol  : variable field
[error] location: class TestObject
[error]     int i = TestObject.field;

1 个答案:

答案 0 :(得分:16)

Scala字段是私有变量,具有相同名称的getter以保持不变性。

public class JavaTest
{
  public static void main(String[] args)
  {
    int i = TestObject.field();
  }
}