https://kotlinlang.org logo
#announcements
Title
# announcements
n

Nir Golan

07/02/2019, 7:43 AM
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

gildor

07/02/2019, 7:45 AM
same for memory
choice between of nullable/lateinit is depends on your case, not on performance
n

Nir Golan

07/02/2019, 7:46 AM
thanks
d

diesieben07

07/02/2019, 7:46 AM
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

gildor

07/02/2019, 7:46 AM
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

Nir Golan

07/02/2019, 7:53 AM
does
isInitialized
cost more then null checks?
d

diesieben07

07/02/2019, 7:54 AM
No, it's a compiler intrinsic that just does a null check
👍 1
g

gildor

07/02/2019, 8:00 AM
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

diesieben07

07/02/2019, 8:01 AM
Yes,
lateinit
is a kludge for using frameworks that do "magic field injection", often based on annotations.
m

Miguel A. Ruiz

07/02/2019, 8:11 AM
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

Nir Golan

07/02/2019, 8:20 AM
thats something we didn't thought on
thanks
m

Miguel A. Ruiz

07/02/2019, 8:22 AM
you are welcome
r

Ruslan Demyanov

07/02/2019, 8:27 AM
Is it any analog of
let
function for lateinit property or just if isInitialized check? Or maybe some extension for it?
d

diesieben07

07/02/2019, 8:27 AM
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

Ruslan Demyanov

07/02/2019, 8:32 AM
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

diesieben07

07/02/2019, 8:35 AM
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

Ruslan Demyanov

07/02/2019, 8:37 AM
Thanks for explanation
3 Views