Hey people, I have a “when” question. When faced ...
# announcements
c
Hey people, I have a “when” question. When faced with this a colleague of mine recommended a one line refactor but I can’t achieve it because.
Copy code
fun fillFieldsForAttribute(attribute: Map<String, Any>): Any? {
    when (localVariable) {
        is TruParameter -> {
            localVariable.update(attribute)
        }
        is TruVoltage -> {
            localVariable.update(attribute)
        }
        is TruBatteryState -> {
            localVariable.update(attribute)
        }
    }
    return localVariable
}
The classes referenced after “is” are all a subclass of “TruAbstract” which contains “update” what I tried was
Copy code
(localVariable as TruAbstract).update(attribute)
return localVariable
and this does not work Do you see any good idea for a refactor here?
Solved
g
Hi, could you share your solution? We have a similar problem. Thanks!
c
So, the thing is when I tried casting this to the parent it didn’t work because the implementation of “update” was in the parent of the parent of TruAbstract
My solution is quite different now
What I do is that, instead if passing in my value, now I actually wrote this method inside of the root class (the parent of the parent) and I work with “this”
Copy code
fun updateParameter(
    topicMap: Map<String, Any>,
    messageConstantKey: String
) {

    try {
        topicMap.getParameterFromMap(messageConstantKey)
            ?.let { attribute ->
                this.update(attribute)
            }
    } catch (ex: Exception) {
        this.updateValue(topicMap, messageConstantKey)
    }
}
Because I know the type for sure (it’s itself) I don’t need to worry with casting
it was an architecture problem 😛
g
Ok, thank you! 👌
c
If you want to share and did my explanation helped?
g
Our problem is a little bit different, we have two methods and each one takes a parameter which is a subclass of an abstract object. We are forced to use the 'when' syntax when we need to call these methods.
c
Sounds very similar to my problem
Can you call this method from the subclass?