How to check if a “lateinit” variable has been initialized?

前端 未结 8 676
执念已碎
执念已碎 2020-11-29 15:37

I wonder if there is a way to check if a lateinit variable has been initialized. For example:

class Foo() {

    private lateinit var myFile: Fi         


        
8条回答
  •  不知归路
    2020-11-29 16:16

    kotlin.UninitializedPropertyAccessException: lateinit property clientKeypair has not been initialized
    

    Bytecode says...blah blah..

    public final static synthetic access$getClientKeypair$p(Lcom/takharsh/ecdh/MainActivity;)Ljava/security/KeyPair;
    
    `L0
    LINENUMBER 11 L0
    ALOAD 0
    GETFIELD com/takharsh/ecdh/MainActivity.clientKeypair : Ljava/security/KeyPair;
    DUP
    IFNONNULL L1
    LDC "clientKeypair"
    INVOKESTATIC kotlin/jvm/internal/Intrinsics.throwUninitializedPropertyAccessException (Ljava/lang/String;)V
        L1
    ARETURN
    

    L2 LOCALVARIABLE $this Lcom/takharsh/ecdh/MainActivity; L0 L2 0 MAXSTACK = 2 MAXLOCALS = 1

    Kotlin creates an extra local variable of same instance and check if it null or not, if null then throws 'throwUninitializedPropertyAccessException' else return the local object. Above bytecode explained here Solution Since kotlin 1.2 it allows to check weather lateinit var has been initialized or not using .isInitialized

提交回复
热议问题