Kotlin Basics - Lazy initialization

Kotlin Basics - Lazy initialization

In Kotlin, an object can only be created when it is called, otherwise no object creation

The lazy () block

fun main() {

    val bookInstance1 = Book(
        "Rogue Lawyer", "John Grisham", 2015
    ) // prints Book Rogue Lawyer class is called

    val bookInstance2 by lazy {
            "The Rain maker", "John Grisham", 1995



class Book(
    var name: String,
    var author: String,
    var year: Int
) {

    init {
        println("Book $name class is called")

    fun getBookDetails() {
            "-------------------------- \n" +
                    "Book Name : $name \n" +
                    "Author Name : $author \n" +
                    "Published Year :$year \n" +

In the above code, the bookInstance1 object is created when the object is initialized and bookInstance2 object is not created because the bookInstance2 is inside the lazy block which means bookInstance2 will be created only when bookInstance2.getBookDetails() is called

Things to note

  • the lazy function takes a lambda and returns the lazy instance

  • It can be used only with non-null variables

  • val is allowed: var is not allowed

  • object will be initialized only once and return the same values from the cache memory

  • prevents unnecessary initialization of objects

Please leave your comments to improve.

Enjoy and happy coding