late vs lateinit: contrasting late initialisation in Dart and Kotlin

Chahat Gupta
2 min readJul 9, 2023

--

Late initialisation in null-safe languages refers to declaring a variable without assigning it an initial value. It is different from other languages where not providing an initial value simply defaults to null or undefined.

Late initialisation is when you explicitly guarantee that by the time the variable is accessed it will be assigned some value and the compiler trusts you.

Let’s see some code — declaring late variables in Dart and Kotlin:

// late in Dart

late String name;

void main() {
name = 'John Wick';
print(name);
}
// lateinit in Kotlin

lateinit var name: String

fun main() {
name = "John Wick"
println(name)
}

There are a couple of scenarios where this approach might be useful:

  1. When we do not know the value of a variable at the time of declaration.
  2. When we want to delay the creation of the object in case it is CPU or memory expensive.

But wait, can’t we just use null for both the cases? The answer is yes but not in this blog.

Although the objective of the two are similar in their respective languages, I like the Kotlin version comparatively more. The reason is that I find it more logically correct and it does not break rules like the Dart version. Let me explain.

  1. When using the lateinit modifier in Kotlin you can check if the variable is initialised using the .isInitialized getter. Same is not possible with the late modifier in Dart.
  2. Kotlin does not allow late initialisation with nullable types.
  3. All variables in Kotlin using the lateinit modifier must be mutable. This makes sense as the value assigned to the variable will actually change. Whereas in Dart, you may declare a final lateinit variable that can be assigned only once. Assigning it a second time results in a runtime error.
// final late re-assignment in Dart

late final String name;

void main() {
name = 'John Wick'; // no problem till here
name = 'Tony Stark'; // oops!
print(name);
}
// output
Uncaught Error: LateInitializationError: Field 'name' has already been initialized.

The Dart version seems like too much manual responsibility to me.

What do you think?

Conclusion

In this blog, I aimed to highlight the similarities and differences between late initialisation techniques in Kotlin and Dart, the two most prominent languages in the Mobile Tech industry today.

Although after years of working with both Kotlin and Dart, I have come to the realisation that late initialisation is a practice that I strongly dislike. I would really like to write another blog contrasting these two against null.

Let me know what you think about this one and let’s meet in another blog. Happy coding!

--

--

Chahat Gupta
Chahat Gupta

Written by Chahat Gupta

Mobile Tech Lead specialising in Android, iOS, and Flutter. Sharing insights and learnings on mobile development to inspire and elevate tech professionals.

No responses yet