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 ...