'How to get Context in onViewCreated

I'm attempting to configure a RecyclerView adapter and I have a line of code

val decorator = AppCompatResources.getDrawable(context, R.drawable.decorator)

This line of code will not work however as context is nullable and getDrawable requires context. I can think of 4 potential options for getting a non-nullable context in onViewCreated:

  1. Wrap the code in context?.let {}
  2. Wrap the code in activity?.applicationContext?.let {}
  3. Use requireContext()
  4. Get context from my application. My application class includes the following code:
    override fun onCreate() {
        super.onCreate()
        instance = this
    }

    companion object {
        lateinit var instance: MyApp
            private set

        val context: Context
            get() = instance
    }

My dev lead is not a fan of requireContext, and will request that I remove it if he sees it in a pull request. Is he wrong? Help me get Context smart, which of these options are the best and why?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source