Part 03 / Topic 6 of 8
lateinit var versus a nullable type
lateinit var solves a different problem than String?. It's for a var — a top-level
property, a class property, or a local variable inside a function, all three accepted by this
compiler — that will definitely be set before anyone reads it, just not at the moment it's
declared: a session token set the instant login succeeds, a config value set once at startup.
Declaring it lateinit keeps its type as the plain, non-null type (String, not String?)
everywhere it's used after that point — no ?. scattered through code that knows, for a fact,
the value is there.
lateinit var sessionToken: String
// ... later, once login actually happens:
sessionToken = "TOK-9f31"
Read it before it's set, and you get a dedicated exception that says exactly what went wrong — not a bare NPE:
$ kotlinc LateinitTest2.kt -include-runtime -d lt2.jar
$ java -jar lt2.jar
about to read an uninitialized lateinit var
Exception in thread "main" kotlin.UninitializedPropertyAccessException: lateinit property sessionToken has not been initialized
at LateinitTest2Kt.main(LateinitTest2.kt:4)
at LateinitTest2Kt.main(LateinitTest2.kt)
::property.isInitialized checks without crashing, when you genuinely need to know in advance:
println(::sessionToken.isInitialized) // false, before login; true, after
Two restrictions, both real compiler errors:
$ kotlinc LateinitPrimitive.kt -d ltp
LateinitPrimitive.kt:2:5: error: 'lateinit' modifier is not allowed on local variables of primitive types.
lateinit var retries: Int
^^^^^^^^
$ kotlinc LateinitVal.kt -d ltv
LateinitVal.kt:2:5: error: 'lateinit' modifier is allowed only on mutable properties.
lateinit val sessionToken: String
^^^^^^^^
lateinit only works on var (never val — a val that could still be assigned later isn't
really a val), and never on a primitive type (Int, Boolean, Double, ...) — the JVM has
no "uninitialized" representation for those below the object layer, only for references.
Use lateinit var for "definitely there soon, not there yet"; use a nullable type (String?)
for "might genuinely never exist" — a referral code most users never enter is not "not set up
yet," it's legitimately absent, forever, for that user:
val referralCode: String? = null
println("referral code = ${referralCode ?: "none"}")
$ kotlinc 06_lateinit_vs_nullable.kt -include-runtime -d 06.jar
$ java -jar 06.jar
initialized before login? false
reading before login threw: lateinit property sessionToken has not been initialized
initialized after login? true
session token = TOK-9f31
referral code = none
Full program: examples/06_lateinit_vs_nullable.kt.
Done here? The practice set for Part 3 — including the solutions — is on the part page.