Reputation: 7537
I want to merge two records created with the same constructor.
Record A gets initialized with values for the fields a,b,c
while record B gets initialized with a value only forfoo
.
The constructor has default values for all fields, so both records have a,b,c,foo
as fields.
Now I want to merge Record B "on top of" A, such as the new record, will contain a,b,c
from A and foo
from B.
What actually happens, is that B completely overrides the values in A (admittedly, this sounds logical).
Is there a known / easy way to merge the records, excluding default values? I am thinking something along writing a function that recognizes the constructor, finds the default values from a config file, and has some logic to exclude default values, but that sounds error prone (how do I diffrentiate between a default value, and a value that is legitimate, but is exactly like the default?).
Also, I am working in an existing codebase and would like to make changes as small as possible.
Upvotes: 0
Views: 199
Reputation: 2187
i think you want mergeWith
docs
it might even make sense to hang a method off of either / both type A and type B to expose your custom merge logic. this would allow you to more easily identify default values (since presumably they'll be in scope) as well as provide convenient access.
usage would look something like:
a instanceof A; //=> true
b instanceof B; //=> true
a.mergeB(b); //=> a w/ some or all of b's data
b.mergeA(a); //=> b w/ some or all of a's data
Upvotes: 1