How to know if a variable has been initialized (Kotlin)?

0

I'm using Kotlin and at the beginning of my application I declare a variable that I initialized later, with the aim of not declaring it as null at the beginning and thus avoiding the annoying signs of Nullability (!!):

private lateinit var variableName: Type

At a certain point I want to know if the variable has already been initialized to perform a certain instruction, otherwise I will ignore it.

I already try to use LET, but it does not work for me.

variableName.let{ código }

I pretend to know if you can do something similar to

if(variableName.isInitialized){}
    
asked by dámazo 01.10.2017 в 19:22
source

3 answers

2

In version 1.2 of kotlin that is currently in its beta2 version, functionality has been included to know when a lateinit variable has already been initialized.

lateinit var file: File
// ...
if (::file.isInitialized) {
  ...
}
    
answered by 31.10.2017 в 21:09
1

You can not use lateinit before initializing the variable, so check if it is initialized with lateinit throw UninitializedPropertyAccessException . In your case you can not use lazy as it can only be assigned the value in the definition of the variable and the value can not change.

The only option I see is changing it to nullable and checking if this null :

private var variableName: Type?

    //..

    if(variableName.isNull())
    {

    }
    
answered by 02.10.2017 в 17:27
0

Keep in mind that when declaring variables of primitive type like int , boolean , float , etc ... by default they have a value. In the case of int is 0 , boolean is false and float is 0.0f . In the case of variables of type object, its default value is null .

Knowing this you only have to compare the value of the variables with their default value, if the variables are equal to their default value then they have not been initialized. And if a variable is initialized with its default value, it is as if it were not. For example, if you initialize a variable of type int with zero, it is like this is not initialized. The same happens with an object that you initialize with null

if(variableName == null){
    // variable no inicializada
}
    
answered by 01.10.2017 в 20:44