In the Kotlin language we, by default, have to initialize each variable when it is introduced. To avoid this, the lateinit
keyword can be used. Referring to a lateinit
variable before it has been initialized results in a runtime exception.
lateinit
can not, however, be used with the primitive types. Why is it so?
A short answer is that with primitives you can always use
0
as the default, and with nullable typesnull
as a default. Only non-nullable non-primitive types may needlateinit
to work around the type safety system.Actually, there is no need for initializing a variable in Kotlin as long as it has a value before the first access and it can be statically proved. Which means this code is perfectly valid:
But there are (rare) cases when the initialisation cannot be statically proved. The most common case is a class field which uses any form of dependency injection:
For object types, Kotlin uses the
null
value to mark that alateinit
property has not been initialized and to throw the appropriate exception when the property is accessed.For primitive types, there is no such value, so there is no way to mark a property as non-initialized and to provide the diagnostics that
lateinit
needs to provide. (We could try to use a separate marker of some kind, but that marker would not be updated when initializing the field through reflection, which is a major use case oflateinit
).Therefore,
lateinit
is supported for properties of object types only.