How does Kotlin's `lazy` implementation work without getValue and setValue?

Viewed 285

In Kotlin properties with pre-set custom get/set behavior are implemented using delegated properties. According to the doc, a delegate for a property is just a class with getValue and setValue methods

But when I looked inside the implementation of lazy, I only found value property. So I tried to implement a delegate this way myself. It failed to compile, because getValue and setValue were not implemented explicitly. How does the official implementation of lazy work then?

1 Answers

getValue is declared as an extension function (yes that works too!) on all Lazy<T>s:

Source:

public inline operator fun <T> Lazy<T>.getValue(thisRef: Any?, property: KProperty<*>): T = value

As you can see, it returns value, which is exactly what you would expect.

There is no setValue, and that is fine. That just means you can't use lazy { ... } as a property delegate for a var, and you indeed cannot:

var foo by lazy { 10 } // compiler error

After all, this doesn't make much sense anyway.

Related