Hoinzey

Javascript. Kotlin. Android. Java

Kotlin: Lazy init

Lazy initialization is a common pattern where we only create a part of an object the first time it is asked for. The most obvious reason to do this is that it is an expensive operation to carry out and may not be needed immediately after the creation of the object.


Below are 2 examples of how we can do this in Kotlin. We are going to use a dummy Amazon account object and our lazy value will be our order history. You could easily go to the Amazon site and not view your history, so what is the reason to load it the first time you create the user.


Using a backing property

Below we use a backing property to achieve our lazy loading. This is a fairly common technique and works well for our example but if you imagine having several of these in an object it can get cumbersome.

                    
    class MyAmazonAccount(val accountId: Long) {

        private var _orderHistory: List? = null

        val orderHistory: List
            get() {
                if(_orderHistory == null) {
                    _orderHistory = loadOrderHistory(this)
                }

                return _orderHistory!!
            }
    }
                

Using a delegated property

Lazy returns an object that has a method called getValue with the proper signature, so we can combine this with by to create a delegated property. The lazy function is thread-safe by default but you can pass different flags to it if you need certain locks or if you don't need it to lock at all.

                    
    class MyAmazonAccount(val accountId: Long) {

        val orderHistory by lazy { loadOrderHistory(this) }
    
    
        fun loadOrderHistory(account: MyAmazonAccount): List? {
            return mutableListOf()
        }
    }