I see that my team mates are using `lateinit var` ...
# announcements
e
I see that my team mates are using
lateinit var
for things that should be downloaded first. Is it good practice? (I don’t like it)
m
IMO lateinit var should only be used when there is a guarantee that variable will be initialized immediately (just not in the constructor)
for example in
onCreate
method on Android which is called pretty much immediately after constructor
e
Any good thoughts to explain it?
I understand they don’t want to have nullable and they are trying to guard with
isInitialised
p
What happens if download fails? It throws that variable has not been initialised? That does not seem logical from the exception.
e
it just ignores logic that is there or tries redownload
p
Could you show the code? I don't understand why a lateinit var is needed if the logic is skipped on failure. Where is the variable accessed then? Or are there checks everywhere if the download succeeded?
g
My thumb of rule: if you got a case that you need
isInitialised
than you misuse lateinit and should use nullable instead
1
👍 7
The language provides great tools to handle nullability, so it’s a lot easier and safer to use nullable, than conditional lateinit
p
I wonder what's the use case that they added
isInitialised
for because like you said if you use it you should probably use nullable type instead.
g
Because it may be needed for some rare cases, for example for libraries that set lateinit, but most probably it’s not needef for common code
e
Thank you for comments, if it would be official Kotlin guides about usage of
lateinit var
then it would be great
s
My rule of thumb is like Andrey's. Only use lateinit if you don't control the object's lifecycle (eg Activity), a 3rd party library injects upon construction (eg Dagger) or a lateinit represents an expensive resources (still, prefer 'lazy' in this case). And I agree, it's a major codesmell when you need 'isInitialized'.