I was curious about a piece of code in Compose. Th...
# getting-started
a
I was curious about a piece of code in Compose. There is a ‘function literal with receiver’
SaverScope.Save
I don’t grok. Here is the easy part:
Copy code
interface Saver<Original, Saveable : Any> {
    fun SaverScope.save(value: Original): Saveable?
}

fun interface SaverScope {
    fun canBeSaved(value: Any): Boolean
}
Saver
function below what confuses me, specifically
save.invoke(this,value)
Copy code
fun <Original, Saveable : Any> Saver(
    save: SaverScope.(value: Original) -> Saveable?,
): Saver<Original, Saveable> {
    return object : Saver<Original, Saveable> {
        override fun SaverScope.save(value: Original) = save.invoke(this, value)
    }
}
The object instantiation is implementing
save
with
save.invoke(this, value)
but afaict
this
is not
SaverScope
, it is an object of type
Saver
. Can somebody clarify what is happening here?
j
>
this
is not
SaverScope
It is. The
this
in
save.invoke(this, value)
refers to the receiver of the
save
function implemented in the anonymous object. It doesn't refer to the anonymous object itself (you would need some qualified
this@something
to access the outer
this
in this case).
👍 1
a
Thanks!