Home > Blockchain >  OOP in Kotlin (lateinit)
OOP in Kotlin (lateinit)

Time:08-14

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)
    }
}

CodePudding user response:

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 ..

  • Related