DEV Community

Cover image for Who Owns the Value? Choosing Between lateinit and by lazy in Production Kotlin
Android Expert
Android Expert

Posted on Originally published at Medium

Who Owns the Value? Choosing Between lateinit and by lazy in Production Kotlin

Both keywords postpone initialization. Teams still reach for the wrong one all the time, and the bug usually shows up as a crash report with a stack trace that points at a line that looks perfectly innocent.

The fix is not memorizing syntax. It is asking one question before you type either keyword.

who-owns-the-value

The one question

Who is responsible for providing the value?

With lateinit, you tell the compiler: "I don't have this yet. Something else will assign it later." The property starts with no backing value, and you must assign it before the first read.

With by lazy, you tell the compiler: "I know how to build this. Build it only when someone asks, then remember the result." The initializer runs on first access and the result is cached.

So the real difference is not “both delay initialization”. It is when and by whom:

  • lateinit: assigned later by external code.
  • by lazy: created later by the property itself.

If you cannot answer who owns the initialization, the code will be hard to reason about, and that is the failure we are actually trying to avoid.

What each one compiles to

A short mental model helps when you debug.

class Example {
    lateinit var token: String
    val parser: JsonParser by lazy { JsonParser() }
}
Enter fullscreen mode Exit fullscreen mode
  • lateinit var keeps a plain nullable field. The generated getter checks for null and throws UninitializedPropertyAccessException if nobody assigned it. There is no wrapper object.
  • by lazy allocates a Lazy<T> delegate object per property. Each read goes through getValue, which checks an internal flag and returns the cached value.

That explains two practical differences. lateinit is a var you can reassign. lazy gives you a val, built once, that you cannot reset.

two-lifecycles

Use lateinit for values someone else provides

The classic cases all involve a framework or container that constructs your object first and hands over collaborators afterward.

Field injection

@AndroidEntryPoint
class CheckoutActivity : AppCompatActivity() {

    @Inject lateinit var paymentGateway: PaymentGateway

    override fun onCreate(savedInstanceState: Bundle?) {
        // Hilt injects while super.onCreate() runs (via an OnContextAvailableListener),
        // so touching paymentGateway before this call would throw.
        super.onCreate(savedInstanceState)
        paymentGateway.warmUp()   // Safe: injection has completed
    }
}
Enter fullscreen mode Exit fullscreen mode

You do not own the construction of an Activity. The system does, so a constructor parameter is not an option. lateinit is an honest description of that constraint.

Views owned by the lifecycle

class ProfileFragment : Fragment(R.layout.fragment_profile) {

    private lateinit var adapter: ProfileAdapter

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        adapter = ProfileAdapter(::onItemClicked)
        view.findViewById<RecyclerView>(R.id.list).adapter = adapter
    }
}
Enter fullscreen mode Exit fullscreen mode

The value cannot exist before onViewCreated, and the Fragment decides when that happens.

Use by lazy for values the class can build itself

If the class already has everything it needs, lazy keeps construction cost out of the hot path.

class ReportExporter(private val appContext: Context) {

    private val csvFormatter: CsvFormatter by lazy {
        CsvFormatter(
            // Configuration.locales needs API 24; the compat call works on older
            // devices, and the list can be empty, so fall back explicitly.
            locale = ConfigurationCompat.getLocales(appContext.resources.configuration)[0]
                ?: Locale.getDefault(),
            delimiter = ';'
        )
    }

    fun export(rows: List<Row>): String = rows.joinToString("\n", transform = csvFormatter::format)
}
Enter fullscreen mode Exit fullscreen mode

If no user ever exports a report during the session, the formatter is never created. Nobody has to remember to call an init() method either, because there is no externally assigned state to forget.

You probably use lazy already without noticing: by viewModels(), by activityViewModels() and by navArgs() are all lazy delegates.

Real-world failure modes

1. Reading a lateinit before it is assigned

This is the textbook crash, and it is almost always a lifecycle ordering mistake.

class SearchFragment : Fragment() {

    private lateinit var searchAdapter: SearchAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        viewModel.results.observe(this) {
            searchAdapter.submitList(it)   // May fire before onViewCreated
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        searchAdapter = SearchAdapter()
    }
}
Enter fullscreen mode Exit fullscreen mode

The observer was registered against the Fragment, not the view, so cached LiveData can deliver a value before the adapter exists. The result is UninitializedPropertyAccessException: lateinit property searchAdapter has not been initialized.

Two safer approaches:

// Option A: observe with the view lifecycle, after the adapter exists.
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    searchAdapter = SearchAdapter()
    viewModel.results.observe(viewLifecycleOwner) { searchAdapter.submitList(it) }
}

// Option B: the adapter has no view dependency, so the Fragment can own it.
// It outlives the view, so detach it when the view goes away.
private val searchAdapter by lazy { SearchAdapter() }

override fun onDestroyView() {
    view?.findViewById<RecyclerView>(R.id.list)?.adapter = null
    super.onDestroyView()
}
Enter fullscreen mode Exit fullscreen mode

Prefer Option A by default. An adapter is view-adjacent state: once attached, the RecyclerView registers an observer on it, so a Fragment-scoped adapter keeps the old RecyclerView reachable after onDestroyView unless you clear adapter as above. Option B is acceptable when you do that teardown, or when the adapter is shared deliberately.

The ownership question still answers who creates the value (the class, so lateinit is not needed). It does not answer how long the value should live. Check both before choosing a delegate.

2. Guarding with isInitialized as a design crutch

if (::searchAdapter.isInitialized) {
    searchAdapter.submitList(items)
}
Enter fullscreen mode Exit fullscreen mode

isInitialized is legitimate in teardown paths, such as a close() that must tolerate a partly constructed object. When it appears throughout normal logic, it usually signals that two different owners are fighting over one property. Split the state, or switch to lazy.

Note also that ::prop.isInitialized is only accessible when the property is declared in the same type or in an enclosing scope that you can reference lexically, so it is not a general-purpose public check.

3. A lateinit view binding that outlives the view

A Fragment instance lives longer than its view. If you keep a lateinit binding, the old view hierarchy stays reachable after onDestroyView, especially when the Fragment sits on the back stack.

fragment-view-lifetime

class OrdersFragment : Fragment(R.layout.fragment_orders) {

    private var _binding: FragmentOrdersBinding? = null
    private val binding get() = _binding!!

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        _binding = FragmentOrdersBinding.bind(view)
    }

    override fun onDestroyView() {
        _binding = null
        super.onDestroyView()
    }
}
Enter fullscreen mode Exit fullscreen mode

A nullable backing field with a non-null accessor is the pattern to prefer here. lateinit cannot be set back to "uninitialized", so it cannot express "this value was valid, and now it must not be used".

4. lazy capturing something that is shorter-lived than the owner

class ImageLoaderHolder(private val activity: Activity) {

    // The delegate retains the lambda until it runs, and the cached
    // object retains Activity forever after that.
    val loader by lazy { ImageLoader(activity) }
}
Enter fullscreen mode Exit fullscreen mode

If ImageLoaderHolder is held by a singleton or a long-lived ViewModel, you have leaked the Activity. Pass applicationContext when the object does not need a UI context, and avoid capturing Activity or View inside a lazy lambda that outlives them.

5. Assuming lazy retries are free, or that exceptions get cached

If the initializer throws, lazy does not store a failure. The next access runs the initializer again.

val database: AppDatabase by lazy {
    Room.databaseBuilder(appContext, AppDatabase::class.java, "app.db")
        .build()           // Might throw on a corrupted or locked file
}
Enter fullscreen mode Exit fullscreen mode

That is sometimes what you want, since transient errors recover. It becomes a problem when the initializer is slow and failing: each caller pays the full cost again, and each one may see a different exception. If failure is permanent, catch it inside the initializer and expose a typed result instead of letting every reader rediscover the problem.

6. Picking the wrong LazyThreadSafetyMode

lazy-thread-safety-modes

The default is SYNCHRONIZED, which is correct for most code and cheap after the first access. You can opt out, but know what you are trading.

// Safe default. The initializer runs once even under contention.
val metrics by lazy { MetricsClient() }

// Tolerates duplicate work. Useful if the initializer is pure and cheap.
val tagFormatter by lazy(LazyThreadSafetyMode.PUBLICATION) { TagFormatter() }

// No locking. Only valid if every access happens on one thread.
val uiScratch by lazy(LazyThreadSafetyMode.NONE) { StringBuilder() }
Enter fullscreen mode Exit fullscreen mode

NONE is attractive in UI code because "it's all on the main thread". That holds until someone calls the property from a coroutine on Dispatchers.Default, and then you get two instances or a half-published object, with a bug that reproduces once in several thousand runs. If the initializer has side effects, such as opening a file or registering a listener, PUBLICATION is also wrong because it may run more than once.

7. Expecting lazy to reset

lazy caches for the lifetime of the owning object. You cannot invalidate it.

// Looks reasonable, but the locale never refreshes after a runtime change.
val dateFormat by lazy { DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault()) }
Enter fullscreen mode Exit fullscreen mode

If the value depends on state that changes, a cached delegate is the wrong tool. Compute it on demand, or hold it in a var that your own code resets.

8. lateinit limits that surprise people

lateinit is allowed only on var properties of non-nullable, non-primitive types. This will not compile:

lateinit var retries: Int        // Error: primitive type
lateinit var name: String?       // Error: nullable type
Enter fullscreen mode Exit fullscreen mode

For primitives, use a default value or Delegates.notNull<Int>(), which throws a clear IllegalStateException when read too early.

9. Process death and configuration change

An Activity or Fragment recreated by the system is a new instance. Every lateinit field and every lazy value starts over. That is correct behavior, but it exposes assumptions: if your code relied on some earlier component having assigned a lateinit on a previous instance, the recreated instance will crash on first read. Anything that must survive recreation belongs in a ViewModel, SavedStateHandle, or persistent storage, not in either delegate.

A decision rule you can apply in review

decision-flow

  1. Can the class build this value from what it already has? If not, someone external must provide it, and lateinit fits.
  2. If it can, is it expensive or only needed on some paths? Then by lazy fits.
  3. If it is cheap and always needed, initialize a plain val in the constructor. Deferral adds a delegate object and a read indirection for no benefit.

Reviewers can apply the same check in the other direction:

  • A lateinit with no framework or injector assigning it is a smell. Prefer a constructor parameter or lazy.
  • A lazy that has to be "kicked" by external code to behave correctly is a smell. The caller is secretly responsible for the value.
  • A lateinit guarded by isInitialized in many places should likely become nullable state or a sealed state type.

Takeaway

Do not decide by “which one delays initialization”. Decide by ownership.

  • Use lateinit for externally assigned values: dependency injection, lifecycle callbacks, and setup that completes after construction.
  • Use by lazy for internally created values that can safely wait until first access.

Once you know who owns the initialization, the choice stops being a style preference and becomes a property of the design.

📱 Go Beyond Using Jetpack Compose

If you’re building on Android, understanding what happens under the hood separates developers who use Compose from those who master it. I highly recommend “Mastering Jetpack Compose Internals”. It’s a deep, architecture-first walkthrough of the composition tree, the slot table, snapshot state, and the runtime that powers modern Android UI — capped off with a full case study building a real app called Mosaic.


Originally published on Medium.

Top comments (0)