Reputation: 3487
I'm a bit new to scala and trying to test some stuff for my company. My Problem is the following: There's a Scala class Test:
class Test {
var id: Int = 0
}
Doing javap -private -c Test:
Compiled from "Test.scala"
public class com.example.Test extends java.lang.Object implements scala.ScalaObject{
private int id;
public int id();
Code:
0: aload_0
1: getfield #11; //Field id:I
4: ireturn
public void id_$eq(int);
Code:
0: aload_0
1: iload_1
2: putfield #11; //Field id:I
5: return
public com.example.Test();
Code:
0: aload_0
1: invokespecial #19; //Method java/lang/Object."<init>":()V
4: aload_0
5: iconst_0
6: putfield #11; //Field id:I
9: return
}
As you can see, the id variable itself is marked as private. How can I force Scala to mark it as protected? There's really no way round...
Upvotes: 3
Views: 490
Reputation: 49705
Try writing the class like this:
import scala.reflect.BeanProperty
class Test {
@BeanProperty var id: Int = 0
}
Then you'll get a generated setId
and getId
methods, as per a "standard" POJO.
Upvotes: 2
Reputation: 40461
Because of the uniform access principle, all fields are private in Scala. But the generated methods aren't. So you can do in Java
:
Test test = new Test();
test.id_$eq( 23 );
System.out.println( test.id() ); //Should print "23"
If you find it ugly, you can use Java Beans accessors.
Upvotes: 7