Roadmap · Stage 1: Kotlin and DSA basics

What Is the Difference Between lazy and lateinit in Kotlin, and What Does by Do?

In short: by hands a property’s get and set to another object, called a delegate. lazy is a delegate that runs your block on the first read and keeps the result. lateinit is a plain field you promise to fill before the first read.

Both lazy and lateinit let a property start without a value. They differ in who fills it in.

Say a checkout screen has these two properties:

class CheckoutActivity : AppCompatActivity() {
    private lateinit var binding: ActivityCheckoutBinding
    private val priceFormat by lazy { NumberFormat.getCurrencyInstance() }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityCheckoutBinding.inflate(layoutInflater)
        setContentView(binding.root)
    }
}

binding needs the Activity to be set up first, so you fill it in onCreate(). priceFormat doesn’t need anything from the Activity, so lazy makes it on the first read.

This post covers what by does, how lazy and lateinit work inside, and how to pick one.

What does by do in Kotlin?

A normal property stores its value in a backing field. A delegated property doesn’t. With by, every read calls the delegate’s getValue(), and every write calls its setValue(). That’s the whole contract.

This helps when many properties share the same get and set code. Say your app keeps settings in SharedPreferences:

class BooleanPref(
    private val prefs: SharedPreferences,
    private val key: String,
    private val default: Boolean = false,
) : ReadWriteProperty<Any?, Boolean> {
    override fun getValue(thisRef: Any?, property: KProperty<*>) =
        prefs.getBoolean(key, default)

    override fun setValue(thisRef: Any?, property: KProperty<*>, value: Boolean) =
        prefs.edit().putBoolean(key, value).apply()
}

class Settings(prefs: SharedPreferences) {
    var darkMode by BooleanPref(prefs, "dark_mode")
    var notifications by BooleanPref(prefs, "notifications", default = true)
}

Now settings.darkMode = true saves to preferences, and reading it reads from them. No repeated getters and setters.

The standard library ships a few delegates you’ll see often:

  • lazy { } computes the value on the first read. More on it below.
  • Delegates.observable runs a callback after every set, even when you set the same value again.
  • Delegates.vetoable runs a check before the set and can reject the new value.
  • Delegates.notNull() works like lateinit, but also for Int and other primitive types.
  • A Map: val host: String by map reads map["host"]. A missing key throws NoSuchElementException.

On Android you already use delegates: by viewModels() and Compose’s by remember { mutableStateOf(...) }.

How does lazy work?

lazy takes a block and returns a Lazy<T> object. The first read runs the block and saves the result. Later reads return the saved result.

class Report {
    val summary: String by lazy {
        println("building summary")
        "3 items"
    }
}

Create a Report and nothing prints. Read summary twice and “building summary” prints once.

Three things to know:

  1. It only works with val. var x by lazy { } doesn’t compile, because Lazy has no setValue().
  2. It’s thread-safe by default. If two threads read at the same time, the block runs once and both get the same value. You can change that with LazyThreadSafetyMode. PUBLICATION lets several threads run the block and keeps one result. NONE has no lock and is only safe on one thread. In my test with 8 threads, PUBLICATION ran the block up to 8 times. The default ran it once.
  3. If the block throws, nothing is saved, and the next read tries again.

Here is what the compiler made of Report (Kotlin 2.4.21, from javap):

public final class Report {
  private final kotlin.Lazy summary$delegate;
  public final java.lang.String getSummary();  // calls summary$delegate.getValue()
}

There is no String field. The class holds the Lazy object, and the getter asks it for the value. The default Lazy uses double-checked locking: it takes the lock only while the value isn’t there yet.

If you decompile your own code, you may also see a $$delegatedProperties array. It shows up only when the delegate needs the property object, like BooleanPref in Settings. Report doesn’t have one.

How does lateinit work?

lateinit tells the compiler: this var is non-null, and I’ll set it before I read it. There is no delegate. It’s a normal field with a check in the getter.

class Checkout {
    lateinit var email: String
}
public final class Checkout {
  public java.lang.String email;
  public final java.lang.String getEmail();  // throws if email is null
  public final void setEmail(java.lang.String);
}

The field starts as null. If you read it too early, the getter throws:

kotlin.UninitializedPropertyAccessException: lateinit property email has not been initialized

That’s better than a NullPointerException later, because it names the property. Also notice the field is public: it gets the setter’s visibility, so Java code can read null from it with no check.

The rules, each with its own compiler error:

  • var only, never val.
  • Non-null types only, so String? is rejected. (Why non-null matters is in the null safety post.)
  • No primitive types: lateinit var count: Int fails. Use Delegates.notNull<Int>() instead.
  • No initializer, and no custom getter or setter.

To check if it’s set, use ::email.isInitialized. It works only where you can reach the field: the same class, an outer class, or the same file for a top-level property. From another class it doesn’t compile.

On Android, lateinit fits values that arrive after the constructor: a view binding in onCreate(), a field injected with @Inject, or a test object made in @Before. And since it’s a var, you can set it again.

Which one should you pick?

Diagram: who fills in the value. lazy: the object is created and nothing runs, the first read runs the block once and saves the value, later reads return it; thread-safe by default; a Lazy field in bytecode. lateinit: the field starts as null, your code sets it in onCreate, @Inject or @Before and can set it again, a read before that throws UninitializedPropertyAccessException; not thread-safe; a field plus a null check in bytecode.

Ask who makes the value. If the object can make it from what it already has, use lazy. If it comes from outside after the constructor, like a lifecycle callback, an injector or a test setup, use lateinit.

The trap is that lazy keeps its value for the whole life of the object. That’s fine in an Activity. In a Fragment it isn’t, because Fragments outlive their views:

// Almost right: keeps the first view forever
private val totalText by lazy {
    requireView().findViewById<TextView>(R.id.total)
}

// Right: follow the view's lifecycle
private var _binding: FragmentCartBinding? = null
private val binding get() = _binding!!

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

override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
}

When the user opens another screen and comes back, the Fragment gets a new view, but the lazy still returns the old TextView. Your updates go to a view nobody can see, and the old view stays in memory. A lateinit set in onViewCreated() fixes the wrong view but still holds the old one while the Fragment is in the back stack. The nullable binding, cleared in onDestroyView(), fixes both.

Feature lazy lateinit
Works with val var
Who sets the value? The block, on the first read Your code, after the constructor
Read before it’s set? Can’t happen: the read runs the block UninitializedPropertyAccessException
Nullable and primitive types? Yes No
Thread-safe? Yes by default No
Check if it’s set Keep the Lazy object, call isInitialized() ::name.isInitialized
Can the value change? No Yes, set it again
In bytecode A Lazy field, and a getter that asks it A plain field, and a null check in the getter
Android example A formatter, or an object you may never need binding in onCreate(), @Inject fields

Frequently asked questions

Can I use lateinit with Int or Boolean? No. An Int property compiles to a JVM int, which can’t be null, so there is no way to mark “not set yet”. Use Delegates.notNull<Int>(), which throws IllegalStateException if you read it too early, or give it a default value.

Is lazy slow because of the lock? Only the first read takes the lock. After that, it’s one volatile read and a cast. If a value is only used on the main thread, lazy(LazyThreadSafetyMode.NONE) skips the lock, but I wouldn’t change it unless a profiler shows it matters.

Should I check isInitialized before every read? No. If you need to check it often, the value is really optional, and a nullable type says that more clearly. isInitialized is for rare cases, like cleanup code that can run before setup finished.

What should you remember?

lazy makes the value once, on the first read, and is thread-safe by default. lateinit is a plain field you fill later, with a check that throws if you’re too early. Pick lazy when the object can make the value itself, and lateinit when something outside hands it in. In a Fragment, don’t lazy anything from the view.

If you want to test yourself, try the lazy vs lateinit interview questions. This post is the twelfth topic in Stage 1 of my Android roadmap. The previous one is backing fields and backing properties. If val and var are still fuzzy, start with val vs var.

Which lateinit in your code would you turn into a lazy, or the other way around?