Can someone point me at good explanation of why `l...
# announcements
v
Can someone point me at good explanation of why
lateinit
does not work with the basic types (e.g. `Int`/`Long`/etc)? Googling tells me that it’s because of the way kotlin represents those types, but It’s still fuzzy for me. So I’d appreciate a link or an explanation 🙂
e
Internally, Kotlin marks
lateinit
properties with
@NonNull
and on access checks whether they are null or not. If they are, it throws
PropertyUninitializedException
. As you may understand already, primitive types can't be
null
, because they are not reference types, thus the restriction.
v
That’s where my confusion is coming from - we have nullable primitive types (e.g.
Int?
), and I presume they represented via
Integer
instead of
int
why can’t it be the same for
lateinit
?
e
What's better - having overhead because of boxing just to generify
lateinit
behavior, or handling light primitive values on your own?
v
I don’t have a clear mental model of how things work here, that’s why I ask for explanations 😉. With that preamble - nullable type are treated as a special case and boxing is done for them. Why can’t
lateinit
marked variable be another special case?
k
They should just use the boxed types for lateinit, it happens magically ll over the place anyway.
e
Well, the idea of
lateinit
is to postpone property initialization, because naturally all properties in Kotlin must be initialized on definition or on class construction, so it basically has nothing to do with nullability. Nullability is just how it's internally implemented and why it's confined in applicable types. And yes, it's a terribly looking hack, but, for example, Android couldn't live without it.
k
And they're fail-fast, trying to get the value when it wasn't initialize already immediately throws an error. You can't get that by just initializing a primitive yourself.
e
It's code smell if you use lateinit values when you have access to constructor in the first place. E.g. Android Activity or Fragment or any framework-created component is forced to move initialization to
onCreate()
, that's why they need lateinit property. But then, why would you need lateinit primitives at all? That's just ideologically incorrect.
👎 2
1