Reputation: 9123
This answer says that Object types use the null value on lateinits of Object type. Can someone elaborate on this? What do they mean by "uses the null value"?
Furthermore it says "For primitive types, there is no such value" - why is there no
Upvotes: 2
Views: 89
Reputation: 147971
On the JVM, which was historically the first platform targeted by Kotlin, there is a distinction between the primitive types and classes, or object types.
They have different runtime representations: a primitive value is stored directly in the field, which can only hold one of the corresponding primitive type values (e.g. only true
and false
for boolean
) and has no special representation for a missing value. In comparison, a class-typed field stores an indirect reference to an instance that is allocated somewhere in the heap, and a class-typed field can hold a special null
reference that doesn't point to any instance.
The Kotlin lateinit
properties are compiled to a single field and they internally use the null
value to indicate that the property has not yet been initialized. As primitive-typed JVM fields can't have a null
value, Kotlin doesn't allow lateinit
properties of types that are normally mapped to Java primitives, as that would require a different representation, and no acceptable solution existed, as the other answer says.
Instead, you can use by Delegates.notNull()
to achieve similar behavior with the mapped types.
Upvotes: 5