javascalascala-java-interop

Access scala class fields in java


I have defined the class A in Scala:

class A(var number: Int)

But when I try to access its member field number in java, I get an error:

A a = new A();
a.number = 4;

Results in: java: number has private access in A. If I try to access the number from scala, there is no problem.

What can I do to get around this issue?


Solution

  • Use getter

    a.number();
    

    and setter

    a.number_$eq(4);
    

    instead of the field itself a.number.

    Or

    a.getNumber();
    a.setNumber(4);
    

    if you annotate the field

    import scala.beans.BeanProperty
    
    class A(@BeanProperty var number: Int)
    

    If I try to access the number from scala, there is no problem.

    In Scala when you write a.number or a.number = 4 you actually call getter/setter (this is syntax sugar).