Possible to call Named Arguments dynamically?

I’ve got ~10 of these blocks in a row to check to see if any properties of a data class of robot sensor values has changed enough to care about, and was curious if there was an easier way to do it dynamically. (Kotlin seems to have all these great shortcuts that I’m finding out about!) Reflection seems too slow for a low CPU device.

if(checkChanged(oldSample.m1Tacho, newSample.m1Tacho)) {
    myPropertyChangeSupport.firePropertyChange("m1Tacho", oldSample.m1Tacho, newSample.m1Tacho)
    oldSample = oldSample.copy(m1Tacho = newSample.m1Tacho)
    anyChanged = true
}

Sometimes I use “m1Tacho” as a property, sometimes as a String for the firePropertyChange, sometimes as a Named Argument “name” for the copy()…

Which got me wondering if I could do it all much easier with something like this. (This doesn’t work, because I don’t know how to do the Named Argument copy() dynamically, but you get the idea.)

mapOf(
    "m1Tacho" to ::m1Tacho,
    "m2Tacho" to ::m2Tacho,
    "distance" to ::distance,
   //etc...
).forEach { k, v->
  //... my if checkChanged block not copied 10 times ...
}

I don’t think there is a way to call named arguments dynamically since all the copy calls are statically resolved at compile time. But I think I can help you what you want to achieve in another way.
What you want to achieve is iterating over all sensors of your old sample and firing change events if one changed. I don’t think you need copy at all because all you do is assigning newSample to oldSample in a very inefficient way(; So what you could do is.

for (sensorProp in oldSample::class) {
    val oldSensor = sensorProp.get(oldSample)
    val newSensor = sensorProp.get(newSample)
    if (checkChanged(oldSample, newSample)) {
    
myPropertyChangeSupport.firePropertyChange(sensorProp.name, oldSensor, newSensor)
    anyChanged = true
    }
}
oldSample = newSample

It’s possible that this code doesn’t fit your needs exactly, because I don’t know how your codebase looks in general.
Do you have a GitHub repo for it or something similar, so that I could have a look at it?

If you’re happy to have your data class be mutable, the typical way to do this is with a property delegate. There’s a standard one called observable which takes a callback directly, rather than firing an event. You could subclass that or make your own if you need to broadcast or otherwise decouple the sender from the recipient(s).

I don’t know whether that has too much compile-time or runtime overhead for your system but, as ever, I’d say measure it and see, before trying to write your own, more efficient way

Hope that helps :slight_smile: