Properties, lazy & lateinit Interview Questions

KOTLIN › Language Idioms

What is the difference between lateinit and lazy? When would you use each?

What a strong answer covers: lateinit is for a mutable non-null var you promise to set before use, such as an injected dependency or a view set in onCreate; it has no initialiser and throws if read too early. lazy is for a val computed once on first access by a lambda, thread-safe by default. lateinit can't be used with primitive types or nullable types; lazy can't be reassigned.

What is a backing field in Kotlin, and when does a property have one?

What a strong answer covers: Kotlin properties are accessors; a backing field (referenced as 'field' inside a getter or setter) exists only if the property uses the default accessor or refers to 'field' in a custom one. A computed property like val isEmpty get() = size == 0 has no backing field and no storage. A strong answer mentions the backing property pattern: private val _items mutable, public val items read-only.

What does const val do, and how is it different from a plain val in a companion object?

What a strong answer covers: const val is a compile-time constant: a primitive or String known at compile time, inlined at every use site and usable in annotations. A plain val is a runtime value read through a getter (or a static field). The trade-off: changing a const in a library requires recompiling callers because the old value was inlined.

lazy is synchronized by default. What are the thread-safety modes, and when would you choose a different one?

What a strong answer covers: SYNCHRONIZED (default) locks so the initialiser runs exactly once; PUBLICATION lets several threads run it but only the first result is kept, so the initialiser must be side-effect free; NONE has no locking and is for values only touched on one thread, like UI properties on the main thread, where the lock is pure overhead.

How would you check whether a lateinit property has been initialised, and why is relying on that often a design smell?

What a strong answer covers: ::prop.isInitialized works for lateinit properties accessible in the same scope. Needing it usually means the property isn't really 'always set before use' and should be nullable, lazy, or passed through the constructor. A strong answer prefers constructor injection, and keeps lateinit for framework-driven fields such as DI injection or test setup.

Back to Properties, lazy & lateinit