var --> Can be reassigned variables

val --> Read-only local variables

用編譯後的 Bytecode 來看的話

var 是一個帶有 get/set 方法的 private 變數

private I helloVar

public final getHelloVar()I
   L0
    LINENUMBER 4 L0
    ALOAD 0
    GETFIELD com/cathay/integrationplatform/network/data/Test.helloVar : I
    IRETURN
   L1
    LOCALVARIABLE this Lcom/cathay/integrationplatform/network/data/Test; L0 L1 0
    MAXSTACK = 1
    MAXLOCALS = 1

public final setHelloVar(I)V
    // annotable parameter count: 1 (visible)
    // annotable parameter count: 1 (invisible)
   L0
    LINENUMBER 4 L0
    ALOAD 0
    ILOAD 1
    PUTFIELD com/cathay/integrationplatform/network/data/Test.helloVar : I
    RETURN
   L1
    LOCALVARIABLE this Lcom/cathay/integrationplatform/network/data/Test; L0 L1 0
    LOCALVARIABLE <set-?> I L0 L1 1
    MAXSTACK = 2
    MAXLOCALS = 2

val 是一個帶有 get 方法的 private final 變數

private final I helloVal = 2

public final getHelloVal()I
   L0
    LINENUMBER 5 L0
    ALOAD 0
    GETFIELD com/cathay/integrationplatform/network/data/Test.helloVal : I
    IRETURN
   L1
    LOCALVARIABLE this Lcom/cathay/integrationplatform/network/data/Test; L0 L1 0
    MAXSTACK = 1
    MAXLOCALS = 1

const val 是一個單純的 public final 變數

public final I helloConst = 3

class Test {av
    var helloVar = 1
    val helloVal = 2
    const val helloConst = 3
}
public final class Test {
   private int helloVar = 1;
   private final int helloVal = 2;
   public final int helloConst;

   public final int getHelloVar() {
      return this.helloVar;
   }

   public final void setHelloVar(int var1) {
      this.helloVar = var1;
   }

   public final int getHelloVal() {
      return this.helloVal;
   }
}

results matching ""

    No results matching ""