What's the differences between me using lateinit v...
# announcements
s
What's the differences between me using lateinit var and by lazy, for stuff that gets init'd after create (), like Android, games etc
b
sreich: by lazy initializes the field on first access (according to the function passed), whereas lateinit must be initialized/assigned explicitly
s
Effectively though it's the same especially for short statements
I guess you'd want lateinit instead, if you had to like XL a few statements to create a thing.. Like creating a button or something
b
I think especially for things like android, you would use lateinit when the time of initialization is dependent on external circumstances (availability of contexts e.g.) whereas bylazy could be used anytime, but is simply made lazy to reduze initialization time
m
lateinit
is
var
!
I use
lazy(NONE) { ... }
whenever I can and for example
Disposable
/
Subscription
from RxJava as
lateinit var
if a call to API is made in
onCreate
.
b
i am aware that lateinit is var, I mostly use it for fields which require a context in their constructor for example and therefor are assigned in
onCreate
lazy shouldn't be used when the lazy-block is dependent on the state of the containing object because it isn't really determined when it is called by design (you have to be aware in your code). but aside from this you could use it any other time. But I would not use it everytime because there is still some overhead of lazy to direct initialization, depends on use case