I am in the process of learning Kotlin, and reading about the lateinit
keyword makes me doubt its usefulness. Consider this code:
var testString: String? = null
lateinit var lateTestString: String
fun print() {
print(testString?.length)
print(lateTestString.length)
}
Here the only difference in getting the length of the string is by checking if it is null or not by using the ?.
operator. Is using the lateinit
a shortcut for not having to add that extra question mark when accessing properties or invoking methods? Just by that fact I think it is more worth having to add that extra question mark than getting an exception when accessing the lateinit
one.
More research showed me that lateinit
is good for injections and/or unit tests where the variable has not been initialized yet, but it will be. However, is it not worth having that extra ?.
instead of just .
to not risk an exception?