In Kotlin we have to initialise variable with a value when we declare a variable or we need to assign null. But you dont have to always assign null to a variable depending upon scenario. When you don’t want to initialise a property in the constructor, then in Kotlin there are two essential ways to initialise the property
- lazy initialization
- lateinit
Let’s take one example we have to initialize:
lazy initialization
Variables identified with the const keyword are immutable, as is val. The difference here is that const is applied to variables defined at compile-time. Declaration of a const attribute is just like using the Java static keyword.
|
|
Property getStatusText will not be initialized unless variable is used for the first time. This means variable should be recognize when needed.
lateinit
|
|
The property “gstTax” can be initialized later in the constructor or in any method before accessing it
But you cannot use lateinit modifier on variables of primitive types or else compiler will throw error_’lateinit’ modifier is not allowed on properties of primitive types_
If the variable is not initialized and we try to access “gstTax”, then in this case it will throw “Caused by: kotlin.UninitializedPropertyAccessException : lateinit property someText has not been initialized”