“lateinit” Variable in Kotlin
In Kotlin, there are some tokens that cannot be used as identifiers for naming variables, etc. Such tokens are known as keywords. In simple words, keywords are reserved and have special meaning to the compiler, hence they can’t be used as identifiers. For example,
- as
- break
- class
- continue
- lateinit
“lateinit” keyword:
The “lateinit” keyword in Kotlin as the name suggests is used to declare those variables that are guaranteed to be initialized in the future.
Properties of primitive data types (e.g., Int, Double), as well as nullable properties, can’t be declared using “lateinit”.
“lateinit” variable:
A variable that is declared using “lateinit” keyword is known as “lateinit” variable.
Syntax:
lateinit var myVariable: String
This article focuses on how to check whether “lateinit” variable is initialized.
How to check if a “lateinit” variable has been initialized?
In Kotlin 1.2 version some changes were made using which we can check whether “lateinit” variable is initialized with the help of isInitialized method.
Syntax:
myVariable.isInitialized
Return value:
false: If myVariable is not initialized yet
true: If myVariable is initialized
Example 1:
In the below program, we have declared “myVariable” using “lateinit” keyword. Before initialization, we checked whether this variable is initialized using isInitialized method. Later we have initialized it as “GFG”. Now we are checking again whether this variable is initialized.
Kotlin
// Kotlin program to demonstrate how to check // whether lateinit variable is initialized or not class GFG { // Declaring a lateinit variable of Int type lateinit var myVariable: String fun initializeName() { // Check using isInitialized method println( "Is myVariable initialized? " + this ::myVariable.isInitialized) // initializing myVariable myVariable = "GFG" // Check using isInitialized method println( "Is myVariable initialized? " + this ::myVariable.isInitialized) } } fun main(args: Array<String>) { // Calling method GFG().initializeName() } |
Output:
Example 2:
In the below program, we have declared “myVariable” using “lateinit” keyword. Before initialization, we checked whether this variable is initialized using isInitialized method. Later we initialized it as “GeeksforGeeks”. Now we are checking again whether this variable is initialized.
Kotlin
// Kotlin program to demonstrate how to check // whether lateinit variable is initialized or not class GFG { // Declaring a lateinit variable lateinit var myVariable: String fun initializeName() { // Check using isInitialized method println( "Is myVariable initialized? " + this ::myVariable.isInitialized) // initializing myVariable myVariable = "GeeksforGeeks" // Check using isInitialized method println( "Is myVariable initialized? " + this ::myVariable.isInitialized) } } fun main(args: Array<String>) { // Calling method GFG().initializeName() } |
Output:
Please Login to comment...