Techoceanhub logo

What is lateinit keyword in kotlin?(Chapter-12)

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

Share:

Categories

Archives

Related Posts

Array Destructuring

Array Destructuring Array destructuring is a powerful syntax introduced in ES6 that allows you to unpack elements from an array

Read More »

Explore our Affiliated partner links

hostgator website plan

Hostgator

Best Website hosting plans & Best for 24/7 support.

hostinger webhosting plan

Hostinger

Reasonable website hosting packages for small business & 24/7 Email support

Elementor pro

Design Worpdress website quickly using Elementor Builder and AI

buy elementor website templates

Buy Elementor Website Template

Buy ready made Elementor Website Template from us & Get Free Elementor pro licence for 1 year .