Hey guys could anyone explain to me why lateinit c...
# random
e
Hey guys could anyone explain to me why lateinit cannot be used with primitive types or non-nullable data types ? and how it is implemented with non-primitive non-nullable data types?
p
You mean cannot be used with nullable or primitives?
e
Yes sir.
p
Is against its purpose logically. Lateinit is basically asking the compiler to break its null-check strictness.A reference is only
non-null valid
, if it has value since it's creation. You use lateinit to break this rule, so the compiler does not enforce the above rule and trust that you will assign some value before using/accessing it. The purpose of lateinit is usually comfort for developers laziness to not handle nullability properly at the cost of writing a few more lines.
❤️ 2
Primitives cannot be null so why even bother to mark them as lateinit, nullability doesn't apply for them
❤️ 2
In general try to avoid
lateinit
or force unwrap
!!
❤️ 1
You really don't need them. There are patterns like
empty object initialization
or simply proper nullability handling with the safe operator
?
, or
lazy
, are better
❤️ 1
e
Thank you so much ❤️
p
👍
k
I'm not entirely convinced about the reasoning for primitives not being allowed to be lateinit. Most of the time, Kotlin tries to treat primitive types and non-primitive types uniformly. In many cases (e.g. when it appears as a parameterized type) an
Int
is implemented as a wrapped
Integer
type. Is there anything technically preventing the compiler from treating a "lateinit Int" as a wrapped Integer which is null when not initialized?
👍 1