开发者

Scala class with field that is marked protected in java

开发者 https://www.devze.com 2023-04-01 01:16 出处:网络
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:

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 its开发者_JAVA技巧elf 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消