Kotlin中的var,val,const val区别

1.var是变量,可对其进行读取和修改(读写)

2.val是常量,只能对其进行读取,而不能修改(读)

3.const只能用来修饰val,并且Const 修饰的val只能定义在top level或者在objects中。top level指的是在最外面的类的外面,表示该常量属于整个文件,而非某个类。object可以指最外面的object和companion object。

从字节码的角度分析:

1.var定义的变量是private,并会生成public的set,get方法

var varObject: String = "varObject"
// access flags 0x2
  private Ljava/lang/String; varObject
  @Lorg/jetbrains/annotations/NotNull;() // invisible

  // access flags 0x11
  public final getVarObject()Ljava/lang/String;
  @Lorg/jetbrains/annotations/NotNull;() // invisible
   L0
    LINENUMBER 9 L0
    ALOAD 0
    GETFIELD test.varObject : Ljava/lang/String;
    ARETURN
   L1
    LOCALVARIABLE this Ltest; L0 L1 0
    MAXSTACK = 1
    MAXLOCALS = 1

  // access flags 0x11
  public final setVarObject(Ljava/lang/String;)V
    // annotable parameter count: 1 (visible)
    // annotable parameter count: 1 (invisible)
    @Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 0
   L0
    ALOAD 1
    LDC ""
    INVOKESTATIC kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull (Ljava/lang/Object;Ljava/lang/String;)V
   L1
    LINENUMBER 9 L1
    ALOAD 0
    ALOAD 1
    PUTFIELD test.varObject : Ljava/lang/String;
    RETURN
   L2
    LOCALVARIABLE this Ltest; L0 L2 0
    LOCALVARIABLE  Ljava/lang/String; L0 L2 1
    MAXSTACK = 2
    MAXLOCALS = 2

2. val定义的变量是private的,会生成public的get方法

val valObject:String = "valObject"
private final Ljava/lang/String; valObject = "valObject"
  @Lorg/jetbrains/annotations/NotNull;() // invisible

  // access flags 0x11
  public final getValObject()Ljava/lang/String;
  @Lorg/jetbrains/annotations/NotNull;() // invisible
   L0
    LINENUMBER 10 L0
    ALOAD 0
    GETFIELD test.valObject : Ljava/lang/String;
    ARETURN
   L1
    LOCALVARIABLE this Ltest; L0 L1 0
    MAXSTACK = 1
    MAXLOCALS = 1

3. const val 定义的变量生成的字节码由public final static 来修饰

const val constObject:String = "constObject"
  public final static Ljava/lang/String; constObject = "constObject"

 

你可能感兴趣的:(Kotlin中的var,val,const val区别)