2

I defined a property in the constructor of my class the following way:

class Step(val message:String = "")

When I try access to message value from Java code y get a visbility error. Why?

4

4 回答 4

1

我猜想在 Java 代码中你试图用step.message. 确实有这样一个领域,而且是私有的。这就是你得到可见性错误的原因。当您在 Scala 中声明“val”字段时,编译器会生成一个字段和访问器方法。所以在java中你应该使用step.message()

于 2010-10-05T14:00:57.030 回答
1

如果您添加 @scala.reflect.BeanProperty 注释,您将获得“自动”获取设置方法

http://www.scala-lang.org/docu/files/api/scala/reflect/BeanProperty.html

scala> class Step(@scala.reflect.BeanProperty val  message:String )
defined class Step

scala> val s = new Step("asdf")
s: Step = Step@71e13a2c

scala> s.message
res6: String = asdf

scala> s.getMessage
res10: String = asdf
于 2010-06-10T08:36:32.337 回答
1

The code is correct, message should be public in this case, but for some reason it is not. So, as a WO you could make it private (just drop the "val") and find a way to produce a getter for this value:

class Step(message: String = ""){
  def getMessage() = message  
}

Or:

class Step(@scala.reflect.BeanProperty message: String = "")

And compile:

> scalac -cp . Step.scala

Then create the calling Java class:

public class SomeClass{
  public static void main(String[] args) {
    Step step = new Step("hello");
    System.out.println(" " + step.getMessage());
  }
}

Then compile and run:

> javac -cp . SomeClass.java
> java -cp "/home/olle/scala-2.8.0.Beta1-prerelease/lib/scala-library.jar:." SomeClass
hello
>
于 2010-06-10T08:58:45.783 回答
0

你试过使用getMessage()吗?也许 scala 正在生成访问器。

于 2010-06-10T08:19:59.070 回答