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

sreich

02/25/2017, 5:25 PM
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

bernhard

02/25/2017, 5:40 PM
sreich: by lazy initializes the field on first access (according to the function passed), whereas lateinit must be initialized/assigned explicitly
s

sreich

02/25/2017, 5:41 PM
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

bernhard

02/25/2017, 5:46 PM
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

mg6maciej

02/25/2017, 6:12 PM
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

bernhard

02/25/2017, 6:38 PM
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
2 Views