Kotlin lateinit
Kotlin lateinit – To declare non null Kotlin Variables without initialization, use lateinit keyword during declaration of the variable. Initialization of that variable could be done at a later point in code.
The lateinit modifier is useful when a property cannot be assigned at the place where it is declared, but you know that it will definitely be initialized before it is used. This is common in Kotlin programs where an object is created later by setup code, dependency injection, Android lifecycle methods, or test initialization methods.
Note : lateinit is supported from Kotlin 1.2. Make sure you are updated to latest Kotlin.
Kotlin lateinit Syntax for Non-Null var Properties
The lateinit keyword is written before var. The property must have a non-null reference type. You cannot use lateinit with val, nullable types, primitive types such as Int, or local variables.
lateinit var variableName: Type
After declaring a lateinit property, assign a value before reading it. If the property is accessed before initialization, Kotlin throws an UninitializedPropertyAccessException.
Example 1 – Kotlin lateinit
In the following example, we will late initialize variable person1.
Kotlin Program – example.kt
/**
* Example to demonstrate lateinit keyword
*/
// variable that we shall initialize at a later point in code
lateinit var person1:Person
fun main(args: Array<String>) {
// initializing variable lately
person1 = Person("Ted",28)
print(person1.name + " is " + person1.age.toString())
}
data class Person(var name:String, var age:Int);
Output
Ted is 28
In this program, person1 is declared as a non-null Person property without assigning a value immediately. The value is assigned inside main() before the property is read, so the program runs successfully.
What Happens When a Kotlin lateinit Property Is Used Before Initialization?
A lateinit property does not automatically create a default value. Kotlin only allows you to postpone assignment. If you try to read the property before assigning it, the program fails at runtime.
lateinit var username: String
fun main() {
println(username)
}
Exception in thread "main" kotlin.UninitializedPropertyAccessException: lateinit property username has not been initialized
Because of this behavior, use lateinit only when there is a clear initialization point before the first access. If a missing value is a valid state in your program, use a nullable type instead.
Check Whether a Kotlin lateinit Property Has Been Initialized
Kotlin lets you check whether a lateinit property has already been initialized by using the property reference with isInitialized. This is useful when a property is assigned later and you need to avoid accessing it too early.
lateinit var message: String
fun main() {
if (::message.isInitialized) {
println(message)
} else {
println("message is not initialized yet")
}
message = "Kotlin lateinit example"
if (::message.isInitialized) {
println(message)
}
}
message is not initialized yet
Kotlin lateinit example
The expression ::message.isInitialized works with a lateinit property reference. It should be used as a guard, not as a replacement for clear program flow.
Kotlin lateinit Rules and Restrictions
The lateinit modifier is intentionally limited. These rules help Kotlin keep the property non-null while still allowing delayed initialization.
lateinitcan be used only withvarproperties.- It cannot be used with
valbecause avalproperty must be assigned only once. - It cannot be used with nullable types such as
String?. - It cannot be used with primitive types such as
Int,Long,Double, orBoolean. - It should be initialized before the first read to avoid
UninitializedPropertyAccessException.
For example, the following declarations are not valid uses of lateinit.
lateinit val name: String // Not allowed: lateinit requires var
lateinit var age: Int // Not allowed: Int is a primitive type
lateinit var email: String? // Not allowed: type is nullable
Kotlin lateinit vs Nullable Property
Both lateinit and nullable properties can represent a value that is not assigned at declaration time. The difference is in meaning. Use lateinit when the property should always have a real value before use. Use a nullable property when the absence of a value is a normal and expected state.
| Requirement | Use lateinit | Use nullable type |
|---|---|---|
| The property should be non-null after setup | Yes | No |
| The value may genuinely be missing | No | Yes |
| You want to avoid safe-call checks everywhere | Yes | No |
| You need to model optional data | No | Yes |
lateinit var databaseName: String
var middleName: String? = null
In this example, databaseName is expected to be assigned before use, while middleName may be absent for a valid reason.
Kotlin lateinit vs lazy Initialization
lateinit and lazy both delay initialization, but they solve different problems. Use lateinit when another part of the program will assign the value later. Use lazy when Kotlin should compute the value automatically the first time it is accessed.
| Feature | lateinit | lazy |
|---|---|---|
| Declaration type | var | Usually val |
| Who initializes it? | Your code assigns it later | The lazy block computes it on first access |
| Can it be reassigned? | Yes | No, when used with val |
| Common use | Lifecycle or setup-based assignment | Expensive value created only when needed |
val configText: String by lazy {
"Loaded only when configText is accessed"
}
Choose lazy for a value that can be calculated on demand. Choose lateinit for a property that must be assigned from outside the declaration, such as during object setup.
Common Kotlin lateinit Use Cases
The lateinit keyword is most useful when a property belongs to an object, but the value is not available at construction time. Common use cases include test fixtures, service objects assigned during setup, and framework-managed properties.
class UserServiceTest {
lateinit var service: UserService
fun setUp() {
service = UserService()
}
fun testUserName() {
setUp()
println(service.getUserName())
}
}
class UserService {
fun getUserName(): String = "Ted"
}
Here, service is not nullable because the test expects it to exist after setup. This is a suitable case for lateinit.
Common Mistakes with Kotlin lateinit Variables
- Reading before assignment: A
lateinitproperty must be assigned before it is used. - Using
lateinitfor optional data: If the value can be missing, use a nullable type such asString?. - Trying to use
lateinitwithval:lateinitworks only with mutablevarproperties. - Using
lateinitwith primitive types: Use a normal initial value, nullable wrapper, or another design for primitive values. - Using
lateinitto hide unclear object design: If a property is always required, consider passing it through a constructor instead.
FAQ on Kotlin lateinit Variables
What does lateinit mean in Kotlin?
In Kotlin, lateinit means that a non-null var property will be initialized later. It lets you declare the property without assigning a value immediately, but the value must be assigned before the property is read.
Can lateinit be used with val in Kotlin?
No. lateinit can be used only with var properties. A val property must be assigned once, so it cannot be marked as lateinit.
How do I check if a lateinit variable is initialized in Kotlin?
Use the property reference with isInitialized, for example ::message.isInitialized. This check helps you avoid reading a lateinit property before it has been assigned.
What exception is thrown when lateinit is not initialized?
Kotlin throws UninitializedPropertyAccessException when a lateinit property is accessed before initialization.
When should I use lazy instead of lateinit in Kotlin?
Use lazy when the value can be computed automatically on first access. Use lateinit when the value must be assigned later by setup code, a framework, or another part of your program.
QA Checklist for Kotlin lateinit Tutorial Examples
- Confirm every
lateinitdeclaration usesvarand a non-null reference type. - Check that each example initializes the
lateinitproperty before reading it, unless the example is intentionally showing the exception. - Use
::propertyName.isInitializedonly with a validlateinitproperty reference. - Do not recommend
lateinitfor optional values that should be represented with nullable types. - Compare
lateinitandlazyonly in terms of initialization behavior, mutability, and ownership of initialization.
Kotlin lateinit Summary
In this Kotlin Tutorial, we have learnt to declare a non null Kotlin Variable without initialization using lateinit keyword with the help of Example Kotlin programs.
Use lateinit when a non-null var property cannot be assigned at declaration time but is guaranteed to be assigned before use. For optional values, prefer nullable types. For values that should be computed only when first needed, prefer lazy.
TutorialKart.com