Muhammad Ahmed AbuTalib
Muhammad Ahmed AbuTalib

Reputation: 4302

Delegates.observable for anonymous functions in kotlin?

I am doing something weird but I have a fleeting feeling it should be possible.

Is the below possible with Kotlin ? (It compiles but doesn't work)

 var delegatedProp: (Int) -> Unit by Delegates.observable({ a-> Unit }) { _, _, newVal ->
        //This is never raised
        //Secondly how should I access the given Int ?
        //newVal.a doesn't seem to compile
    }

I was off the idea that once I invoke delegatedProp(10) , the observable would invoke and I would be able to access newVal.a.

This compiles successfully but the observable is never invoked

Upvotes: 0

Views: 127

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170735

The second lambda will be invoked when you set delegatedProp, i.e.

x.delegatedProp = { print(it) }

({ print(it) } is just an example of something of type (Int) -> Unit). And newVal will be the function you set the property to, in this case { print(it) }. So it doesn't have an .a.

If you want to do something when invoking delegatedProp(10), you just... put those actions into the function:

val delegatedProp: (Int) -> Unit = { a -> /* do whatever you wanted to do with newVal.a */ }

If you want delegatedProp to be a var, but to keep doing your "extra" actions whatever it's assigned to, the easiest way may be a custom getter:

var delegatedProp: (Int) -> Unit = { a -> Unit }
    get() = { a ->
        /* whatever you want to do with a */
        field(a)
    }

Or a setter: it wouldn't create a new lambda each time it's accessed, but either duplicates a bit of code or needs to be explicitly set at least once and not only initialized.

Upvotes: 2

Related Questions