The defination of lateinit keyword is very simple as the name suggest it says ” Late initialization“. This keyword is often considered as one of the best feature which makes kotlin more advantageous to use but we should not confuse it with lazy keyword.
There are many cases when you need to create a variable but you don’t want to initialize it at the time of declaration/creation of the variable because you are sure that the variable will be initialized before its access/usage or in simple terms we can define it as
” The lateinit
keyword is used for late initialization of variables. “.
Now let us see the basic syntax of lateinit keyword:
private lateinit var fruitName: String
The above is a basic simple syntax of lateinit keyword in kotlin. As you can observe above we have not initialized that variable. If you do not initialize a variable in Kotlin, it starts giving you an error “property must be initialized or be abstract” and tell’s us to use lateinit keyword to avoid the error because we are not initializing the variable. Let us see a simple code below.
class MainActivity : AppCompatActivity() {
private lateinit var fruitName: String
fun fetchCourseName(courseId: String) {
print(fruitName);
}
}
lateinit keyword does not allow variable to be initialized at the time it is declared, so that is also the reason it is called lateinit keyword. If in case we initialized a lateinit variable, it gives an error.
private lateinit var fruitName: String="apple" //wrong syntax
Above is a wrong syntax for lateinit keyword. We cannot initialize this variable which is declared as lateinit. This keyword is not a difficult concept to grasp, with practise you can understand it very easily
Feel free to read the post and comment below.
Below is my android application, and is useful for people who has Google Opinion Rewards to cash out. https://play.google.com/store/apps/details?id=com.manasvi.sawant.rewardtocash
If you wanted to create a website, please visit my Fiverr gig link below or contact me at support@techoceanhub.com. https://www.fiverr.com/share/EdZ9L7