Kotlin lateinit Keyword Tutorial

In this section, we will learn what the lateinit keyword is and how to use it in Kotlin.

Note: we’re assuming you’re already familiar with the Kotlin Classes and Objects.

What is lateinit Keyword in Kotlin?

When you have properties in your classes, by default it is necessary to initialize them right at the declaration time! Otherwise if you don’t do that, you’ll get an error.

But you might don’t have the initial values for the properties until at runtime! So what should be done then?

The answer is lateinit keyword!

Using this keyword in front of a property allows us to ignore the initialization of the property until at runtime and the compiler won’t complain anymore.

But remember, we still need to initialize the property at runtime before asking for its value!

Kotlin lateinit Keyword Syntax:

This is how we use the lateinit keyword in Kotlin:

lateinit var propertyName:data-type

Note: the lateinit keyword cannot be used for primitive types! For example, you can set it for properties of type Int, Float, Double etc.

Example: using lateinit Keyword in Kotlin

class Employee{

    lateinit var firstName: String
    lateinit var lastName: String 
    var salary:Double = 0.0

    fun setNameAndLastName(fName:String, lName:String){
        firstName = fName
        lastName = lName
    }

    fun getNameAndLastName():String {
        return "The name is: ${firstName} and the last name is: ${lastName}"
    }

    fun putSalary(slr:Double){
        salary = slr 
    }

    fun giveSalary():Double{
        return salary
    }
}

fun main(){
    var john = Employee()

    john.firstName = "John"
    john.lastName = "Doe"

    john.putSalary(50000.0)

    println(john.getNameAndLastName())
    println(john.giveSalary())
}

Output:

The name is: John and the last name is: Doe

50000.0

How does late initialization work in Kotlin?

Here you can see the firstName and lastName properties are of type String and so we could use the lateinit keyword to declare them (meaning the initialization can happen at runtime).

But the data type of the salary property is primitive and so we can’t use the lateinit keyword on it.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies