Kotlin - How to decide between “lateinit” and “nullable variable”?

后端 未结 4 666
感情败类
感情败类 2020-12-14 00:16

I am confuse for lateinit and nullable variable, which one to use for variable.

lateinit var c: String
var d: String? = null
c = \"UserDefinedTarget\"

// if         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-14 01:10

    These are two completely different concepts.

    You can use lateinit to avoid null checks when referencing the property. It's very convenient in case your properties are initialized through dependency injection, or, for example, in the setup method of a unit test.

    However, you should keep in mind that accessing a lateinit property before it has been initialized throws an exception. That means you should use them only if you are absolutely sure, they will be initialized.

    Nullable types, on the other hand, are used when a variable can hold null.


    class A {
        lateinit var a: String
    
        fun cat() {
            print(a.length)  // UninitializedPropertyAccessException is thrown
            a = "cat"
            print(a.length)  // >>> 3
        }
    }
    
    class B {
        var b: String? = null
    
        fun dog() {
            print(b.length)  // won't compile, null check is obligatory here
            print(b?.length) // >>> null
            b = "dog"
            print(b?.length) // >>> 3
        }
    }
    

    For more information:

    • Late-initialized properties
    • Nullable types

提交回复
热议问题