Search code examples
kotlinkotlin-lateinit

Is the keyword lateinit unnecessary?


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?


Solution

  • lateinit keyword exists to enable one specific scenario: when your field can't be null, but you also can't initialize it in the constructor or with a constant value. It is on you to make sure that you initialize the value before using it. If you don't, you get a special exception with clear meaning.

    The difference between lateinit usage and "normal" nullable field with ?. is that the latter conveys a wrong message about the code: "this thing can sometimes be null". When, in fact, it can't. It is just initialized later than usual (with dependency injection instead of constructor, for example).