The lazy function

Sometimes we need to initialize an object, but we want to make sure that the object will be initialized only once, when it is used for the first time. In Java, we could solve this problem in the following way:

    private var _someProperty: SomeType? = null 
    private val somePropertyLock = Any() 
    val someProperty: SomeType 
    get() { 
        synchronized(somePropertyLock) { 
            if (_someProperty == null) { 
                _someProperty = SomeType() 
            return _someProperty!! 

This construction is a popular pattern in Java development. Kotlin allows us to solve this problem in a much simpler way by providing the lazy delegate. It is the most commonly used delegate. It works only with read-only properties (val) and its usage is as follows:

 val someProperty ...

Get Android Development with Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.