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?
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?
我猜想在 Java 代码中你试图用step.message
. 确实有这样一个领域,而且是私有的。这就是你得到可见性错误的原因。当您在 Scala 中声明“val”字段时,编译器会生成一个字段和访问器方法。所以在java中你应该使用step.message()
如果您添加 @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
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
>
你试过使用getMessage()
吗?也许 scala 正在生成访问器。