1

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?

3
  • 1
    Does Scala generate the getters and setters by any chance? getNumber() and setNumber(number) ? Commented Sep 2, 2020 at 11:23
  • No, not to my knowledge. Commented Sep 2, 2020 at 11:28
  • 2
    @SørenHN It does. Commented Sep 2, 2020 at 11:31

2 Answers 2

9

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).

Sign up to request clarification or add additional context in comments.

Comments

3

You can look at the generated class file when you compile A.scala, that can explain getter number() and setter method number_$eq from Dmytro's answer

// A.scala
class A(var number: Int)
> scalac A.scala
> javap -p A.class
// output of above step

public class A {
  private int number;
  public int number();
  public void number_$eq(int);
  public A(int);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.