Lateinit modifier for local scope variables

in the kotlin documentation, properties page, lateinit properties section, it mentions a lateinit can be used with var keyword inside a class body, top-level property and local variable
I can’t see the difference between these two ways of declaring a var variable

fun foo() {
   var firstName: String
   lateinit var lastName: String

  firstName = "ashraf"
  lastName = "Mohamed"


Both will have a default value of null, no getter, or setter.
so what is the need for it here?

Did you try to actually use these two variables? If you try to access the value of name, your code won’t compile. Accessing name2 compiles, but you will get an exception.

1 Like

@broot thank you for the reply,
my point here is not about the value, sure if I tried to access name2 an exception will be thrown, but I’m talking about if, in a local scope, I’m allowed to define a var name: String without initial value, then I can assign a value later in the function body, why do we need a lateinit modifier in a local scope?
when should I use lateinit var name: String instead of var name: String?

Use cases are really the same as for non-local properties. Sometimes, the logic of our code guarantees that the variable is accessed after it was initialized, but it can’t be easily proofed by the compiler, so it disallows the code.

I can’t provide good examples right now, but often that happens when we have contradicting code branches, so one of them is always executed, but they are not simple if-elses. Probably the easiest way to reproduce the problem is by using higher-order function. Function guarantees the provided lambda is executed, but the compiler doesn’t know that:

fun foo() {
    var result: String
    bar {
        result = "foo"
    println(result) // compile error

fun bar(block: () -> Unit) = block()

This isn’t the best example, because there are better ways to solve this problem than by making the variable lateinit. lateinit is always a last resort solution.

Another example is if you set the variable inside a loop and you know the loop will have at least one iteration.


This explains the need, thank you broot :+1: