The function and difference of attribute modifier in the main construction method of Scala class

As we all know, Scala runs on the Java platform (Java virtual machine). After the scala program is compiled, the corresponding bytecode file will be generated. We decompile the bytecode file into a java file to know what Scala has done for us

  1. Scala source code

    class Test4(a: String)
    
    class Test5(val b: String, var c: String)
    
    class Test6(private val d: String, private var e: String)
    
    class Test7(private[this] val f: String, private[this] var g: String)
    
    class Test8(@BeanProperty val f: String, @BeanProperty var g: String)
    
    //It seems that this kind of writing is useless
    class Test9(@BeanProperty private[this] val f: String, @BeanProperty private[this] var g: String)
  2. Decompiled Java code

    public class Test4
    {
      public Test4(String a)
      {
      }
    }
    
    public class Test5
    {
      private final String b;
      private String c;
    
      public String b(){return this.b; } 
      public String c() { return this.c; } 
      public void c_$eq(String x$1) { this.c = x$1; }
    
    
      public Test5(String b, String c)
      {
      }
    }
    
    public class Test6
    {
      private final String d;
      private String e;
    
      private String d(){return this.d; } 
      private String e() { return this.e; } 
      private void e_$eq(String x$1) { this.e = x$1; }
    
    
      public Test6(String d, String e)
      {
      }
    }
    
    public class Test7
    {
      public Test7(String f, String g)
      {
      }
    }
    
    public class Test8
    {
      private final String f;
      private String g;
    
      public String f(){return this.f; } 
      public String g() { return this.g; } 
      public void g_$eq(String x$1) { this.g = x$1; } 
      public String getF() { return f(); } 
      public String getG() { return g(); } 
      public void setG(String x$1) { g_$eq(x$1); }
    
    
      public Test8(@BeanProperty String f, @BeanProperty String g)
      {
      }
    }
    
    public class Test9
    {
      public Test9(@BeanProperty String f, @BeanProperty String g)
      {
      }
    }

    summary

Main constructor parameters Generated fields Generated method
name:String No fields generated No method generated
val/var name:String Private field Public getter/setter methods
private val/var name:String Private field Private getter/setter method
private[this] val/var name:String No fields generated No method generated
@BeanProperty val/var name:String Private field Public getter/setter methods in Scala and JavaBean
@BeanProperty private[this] val/var name:String No fields generated No method generated

Tags: Scala Java

Posted on Sat, 02 May 2020 15:10:20 -0700 by GooberDLX