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?

oluies
  • 17,694
  • 14
  • 74
  • 117
barroco
  • 3,018
  • 6
  • 28
  • 38

4 Answers4

1

If you add the @scala.reflect.BeanProperty annontation you get "automatic" get and set methods

See 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
oluies
  • 17,694
  • 14
  • 74
  • 117
  • 1
    @isola009 The IDE plugin for Scala still has bugs, sometimes things like that happen. Same thing with the Scala plugins for NetBeans and Eclipse, they also sometimes show bogus errors. – Jesper Jun 10 '10 at 09:51
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
>
olle kullberg
  • 6,249
  • 2
  • 20
  • 31
1

I guess that in the Java code you're trying to access the field with step.message. Indeed, there is such a field, and it is private. That is why you get the visibility error. When you declare 'val' fields in Scala, the compiler generates a field and accessor method. So in java you should use step.message()

IttayD
  • 28,271
  • 28
  • 124
  • 178
0

Have you tried using getMessage()? Maybe scala is generating the accessor.

Edward Dale
  • 29,597
  • 13
  • 90
  • 129