I don't have much experience in Kotlin, but doesn'...
# getting-started
f
I don't have much experience in Kotlin, but doesn't the exception
laneinit
throws defeat the purpose of null safety?
s
If you want null safety, use nullables. Lateinit is used when you have a lifecycle where you initialize the variable after instantiation, but know that it is always set when accessed. For instance, this is quite useful for Android, where you cannot control instantiation of the activity object.
f
I see, thank you
p
See it as a comfort to not having to type the
?
safe operator or doing nullability chech in a variable that you are 99.9 percent is not null. Is just that a value could not be assigned when it was defined and it had to wait a bit later.
On the other side, if it throws, it tells you that the assumption of 99.9 percent non nullness has some caviats. Then, now you know your system has some flaws and that assumption cannot be hold anymore.
s
I'd argue that you should be 100% sure that it is not null when accessed. Everything else is a bug.
d
In my humble opinion, the lateinit will also allow you to have nullsafety with dependencies too (dependency injection).