Safely accessing lateinit properties in Kotlin

Kotlin, by design, doesn’t allow a non-null variable to be left uninitialized during it’s declaration. Whenever you declare a lateinit var, you need to initialize it before you access it. Otherwise, you’ll be greeted with a fancy exception like this:

Exception in thread "main" kotlin.UninitializedPropertyAccessException: lateinit property fullName has not been initialized
	at UninitializedPropertyKt.main(UninitializedProperty.kt:3)

Don’t mistake this for a puny exception. It’ll crash your app. So, how to solve this problem?

Taking the rookie approach

The most lucrative solution to this problem would be to make the property a regular nullable one instead of a lateinit var and assign a value later on. You can do something like this:

var fullName: String? = null

And then just do a plain null check or kotlin null-check operator ? whenever you’re accessing the value.

if (fullName != null) {
    print("Hi, $fullName")
}
var length = fullName?.length ?: 0

Kind of like Java. But hang on a sec, Kotlin is supposed to be better than Java. Also, one of the USPs of Kotlin was eliminating the fiasco caused by a NullPointerException.

So, why go the traditional route?

Here’s a better solution.

Going the Kotlinish way

If you’re using Kotlin 1.2, you can easily check whether a lateinit variable has been initialized or not. If not, well, you can always use the not null approach.

Anyways, here’s how you can check if a lateinit var has been initialized or not:

if (::fullName.isInitialized) {
    print("Hi, $fullName")
}



Wajahat Karim is Pakistan’s first Google Developer Expert in Android. As an experience Android developer, he deeply cares about it and keeps writing and speaking about it. He has written two worldwide 300+ pages books on Android development with more than 100 articles around the internet either on his website or his Medium publications. He is also a passionate contributor in open source and has created many Android libraries used by thousands of developers in their apps worldwide. As active public speaker, he spends lots of time giving talks in conferences and motivating people on Android development. You can find Wajahat most active on Twitter @WajahatKarim where he regularly shares all the good stuff about Android and community building.

Author's picture

Wajahat Karim

🔥 Google Dev Expert (GDE) in Android .
📱 Android Dev. 💻 Open Source Contributor . 📝 Technical Writer . 🎤 Public Speaker

Senior Android Developer

Karachi, Pakistan