https://kotlinlang.org logo
Title
v

Vladyslav Sitalo

10/18/2018, 9:08 AM
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

Egor Trutenko

10/18/2018, 9:11 AM
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

Vladyslav Sitalo

10/18/2018, 9:13 AM
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

Egor Trutenko

10/18/2018, 9:17 AM
What's better - having overhead because of boxing just to generify
lateinit
behavior, or handling light primitive values on your own?
v

Vladyslav Sitalo

10/18/2018, 9:23 AM
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

karelpeeters

10/18/2018, 9:24 AM
They should just use the boxed types for lateinit, it happens magically ll over the place anyway.
e

Egor Trutenko

10/18/2018, 9:34 AM
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

karelpeeters

10/18/2018, 9:41 AM
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

Egor Trutenko

10/18/2018, 9:48 AM
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.
1
👎 2