hi all i have a question regarding best practice, ...
# announcements
n
hi all i have a question regarding best practice, memory, and everything you can share on the subject private var lateinit xyz private var xyz : ABC ?= null what is better?
g
same for memory
choice between of nullable/lateinit is depends on your case, not on performance
n
thanks
d
One big difference is that a nullable property can be set to null again by you or some other code. lateinit is designed for things that are initialized once
g
if nullable is fine for you (so it doesn’t cause too many unnecessary null checks) I would use nullable
even tho it’s possible to check if lateinit is initialized, but I believe that if you have such case better to use nullable
n
does
isInitialized
cost more then null checks?
d
No, it's a compiler intrinsic that just does a null check
👍 1
g
Why I don’t recommend this, is that if you have 1 case, it may require in future 2 cases, so it become not safe to use, but nullable field is always save, compiler will check it for you, not your runtime
d
Yes,
lateinit
is a kludge for using frameworks that do "magic field injection", often based on annotations.
m
If you only need to initialize the variable the first time and you don't need change it more, maybe you can use an immutable approach:
private val xyz: ABC by lazy {}
.
☝️ 1
n
thats something we didn't thought on
thanks
m
you are welcome
r
Is it any analog of
let
function for lateinit property or just if isInitialized check? Or maybe some extension for it?
d
If you need
isInitialized
you probably want a nullable property instead.
The only way to check is indeed
isInitialized
for
lateinit
. What's your use-case?
r
I thought about creating an extension function for lateinit property, but did not have enough knowledge to implement it. The basic idea is to use a function like the
var?.let{}
function, but with lateinit check
d
That's not possible, since the type system has no idea about the
lateinit
status of the property.
You should just use a nullable property, that's what they exist for.
3
r
Thanks for explanation