1. 程式人生 > >Scala 類中屬性和屬性生成的方法的區別

Scala 類中屬性和屬性生成的方法的區別

眾所周知,Scala 是運行於Java平臺(Java虛擬機器)的,那麼Scala程式編譯之後會生成對應的位元組碼檔案,我們將位元組碼檔案反編譯成Java檔案即可知Scala 為我們都做了什麼.

  1. 首先我們有一個Scala 原始檔

    //Scala原始碼
    class Test3 {
      val a = "a"
      var b = "b"
    
      private val c = "c"
      private var d = "d"
    
      private[this] val e = "e"
      private[this] var f = "f"
    
      @BeanProperty var g = "g"
      @BeanProperty
    val h = "h" }
  2. 那麼接下來我們看看這些屬性在反編譯成JAVA原始碼Scala都幫我們做了什麼

    //反編譯後的程式碼
    public class Test3
    {
      private final String a = "a";
      private String b = "b";
    
      private final String c = "c";
      private String d = "d";
    
      private final String e = "e";
      private String f = "f";
    
      @BeanProperty
      private String g = "g"
    ; @BeanProperty private final String h = "h"; public String a() { return this.a; } public String b() { return this.b; } public void b_$eq(String x$1) { this.b = x$1; } private String c() { return this.c; } private String d() { return this.d; } private void d_$eq(String x$1) { this
    .d = x$1; } public String g() {return this.g; } public void g_$eq(String x$1) { this.g = x$1; } public String h() { return this.h; } public String getG(){return g(); } public String getH() { return h(); } public void setG(String x$1){g_$eq(x$1);} }

    總結下:

    Scala欄位 生成的方法
    val/var name 公共的name name_ 方法(僅限於var)
    prviate val/var name 私有的name name_ 方法(僅限於var)
    prviate[this] val/var name
    @BeanProperty val/var name 公共的name getName() name_ setName(…)(僅限於var)