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.isInitializedonly as a guard; if you need it often, the property probably should be nullable. - Prefer
valwithby lazyor constructor parameters when the value never changes.
