Mutable Lazy in Kotlin

We all know and love the Kotlin Programming language. And we use one of its great features — Delegated Properties — relatively frequently (and sometimes we don’t know about it).

One of the most used delegated properties is Lazy, which is used for “lazy” initialization of values (that’s obvious, isn’t it?).

But Lazy in Kotlin has a significant drawback — you can’t update a value of the initialized variable. So, code like this one doesn’t work (pay attention to the “var” keyword in the very first line):

But sometimes we need it! That’s why I created my own implementation of delegated property for this purpose; here it is:

This implementation is quite simple, so I’m not going to explain how it works. Let me just say that our previous example may be rewritten in this way:

And it works like a charm!

--

--

Alexander Shevelev

An Android developer from Yandex LLC, Moscow, Russia. That’s all.