简体   繁体   中英

Scala class with field that is marked protected in java

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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM