Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

OOP in Kotlin (lateinit)

I’m doing a Kotlin tutorial for android app development and in order to use View Bindig it says to replace the MainActivity class with this code:

class MainActivity : AppCompatActivity() {

    lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
    }
}

What is the advantage of initializing the binding object inside the onCreate function?
What would be the difference, if I just initilized it outside of the function, like this:

class MainActivity : AppCompatActivity() {

    val binding = ActivityMainBinding.inflate(layoutInflater)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You will probably get a NullPointerException doing it like that .
reason being LayoutInflater is a System Service which needs a valid context to get initialized with Context#getSystemService .

So if you try to access context Globally inside Activity it will probably be null because Activity’s lifecycle hasn’t been started yet . onCreate is the starting point for Activity . That is the reason behind using lateinit and initializing it inside onCreate . You can only use your activity as a Context with in onCreate() or later in the activity lifecycle till onDestroy.

This goes for all other context bind things like resources , packageManager etc ..

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading