How do you fix "lateinit property has not been initialized" in Kotlin?

← Android answers

A lateinit var was read before anything assigned it. Make sure it is set before first use, or choose a safer pattern such as by lazy, a nullable type or constructor injection.

class ProfileFragment : Fragment() {
    private lateinit var adapter: ProfileAdapter
 
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        adapter = ProfileAdapter()           // assign before any read
    }
 
    fun refresh() {
        if (::adapter.isInitialized) adapter.notifyDataSetChanged()
    }
}
 
// Alternatives
private val adapter by lazy { ProfileAdapter() }   // created on first use
private var adapter: ProfileAdapter? = null        // explicit "not yet" state
  • Lifecycle order is the usual cause: a callback runs before the method that assigns the property, or after the view was destroyed.
  • Use ::property.isInitialized only as a guard; if you need it often, the property probably should be nullable.
  • Prefer val with by lazy or constructor parameters when the value never changes.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required