How does `val answer: String by project` work? `Pr...
# gradle
e
How does
val answer: String by project
work?
Project
interface doesn’t have
getValue()
and
setValue()
, so how does it work as a delegate then?
1
s
It uses this extension function: https://github.com/gradle/gradle/blob/344201c165b776ad8f07a21b21942a9780351b0f/sub[…]-dsl/src/main/kotlin/org/gradle/kotlin/dsl/ProjectExtensions.kt
Copy code
/**
 * Locates a property on [Project].
 */
operator fun Project.provideDelegate(any: Any?, property: KProperty<*>): PropertyDelegate =
    propertyDelegateFor(this, property)
e
@Sam thank you!
blob smile 2
@Sam where
Project.provideDelegate
is called? I don’t follow :)
s
If the object used on the right-hand side of 
by
 defines 
provideDelegate
 as a member or extension function, that function will be called to create the property delegate instance.
(https://kotlinlang.org/docs/delegated-properties.html#providing-a-delegate)
It just happens automatically if
provideDelegate
exists (and is imported)
If
getValue
exists, then properties using
by
will automatically call through to
getValue(...)
. If
provideDelegate
exists, then properties using
by
will instead call
provideDelegate(...).getValue(...)
. 🧙
The docs give some examples of why you might want to use the latter instead of the former
e
@Sam I see.
provideDelegate()
references to
propertyDelegateFor()
. Where it is located?
I don’t see such method in
Project
or in
ProjectDelegate
.
e
Much more clear now, thanks!
s
🐕