Property Reference as a setter lambda fucntion

We can use Foo::bar as (Foo) -> BarType but we can’t use as (Foo, BarType) -> Unit. I want to use as (Foo, BarType) -> Unit.

Feature possibility

I think it’s possible without (big) breaking changes if the Kotlin compiler can resolve this situation: (Sorry, I don’t know how intelligent the Kotlin compiler is)

// with overloads
fun function(lambda: (Foo) -> BarType) {}
fun function(lambda: (Foo, BarType) -> Unit) {}

// if compiler can resolve this invocation as `function(Foo::bar as ((Foo) -> BarType))`,
// I think this is possible without breaking changes
function(Foo::bar)

I’m not sure what do you mean. I assume your data structure is something like this:

interface BarType
interface Foo {
    val bar: BarType
}

Foo::bar is a property accessor, it could be used to access bar property of Foo objects. Therefore, you can say it is some kind of a converter that receives Foo and returns BarType.

And if you look at your first function, it receives exactly this: a converter from Foo to BarType. This is why you can use a property accessor there. Your second function receives a totally different lambda, so why do you think it should be possible to pass a proeprty accessor there?

1 Like

I mean, with those types, I think It should be possible to make a setting accessor via Foo::bar

interface BarType
interface Foo {
    // mutable
    var bar: BarType
}

Ahhh, ok, I missed that “setter” part from the title :slight_smile:

1 Like

This works, but it requires you to use the full Kotlin reflection:

interface BarType
interface Foo {
    var bar: BarType
}
fun function(lambda: (Foo) -> BarType) {}
fun function(lambda: (Foo, BarType) -> Unit) {}

fun main() {
    function(Foo::bar.setter)
}
2 Likes