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

Eugen Martynov

09/02/2019, 5:42 AM
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

Matej Drobnič

09/02/2019, 5:44 AM
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

Eugen Martynov

09/02/2019, 5:46 AM
Any good thoughts to explain it?
I understand they don’t want to have nullable and they are trying to guard with
isInitialised
p

Paulius Ruminas

09/02/2019, 5:48 AM
What happens if download fails? It throws that variable has not been initialised? That does not seem logical from the exception.
e

Eugen Martynov

09/02/2019, 5:51 AM
it just ignores logic that is there or tries redownload
p

Paulius Ruminas

09/02/2019, 6:00 AM
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

gildor

09/02/2019, 6:02 AM
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

Paulius Ruminas

09/02/2019, 6:10 AM
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

gildor

09/02/2019, 6:27 AM
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

Eugen Martynov

09/02/2019, 6:42 AM
Thank you for comments, if it would be official Kotlin guides about usage of
lateinit var
then it would be great
s

streetsofboston

09/02/2019, 1:48 PM
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'.
3 Views