Recursive objects amending with spread operator #505
-
Hi, community! I'm trying to merge multiple dynamic objects and faced an issue. I expect that merged and mergedOther should be identical, but they differ.
Results:
If it's expected behaviour, what is the right way to merge objects? Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
I ran across this myself a few weeks ago! Not only is this expected, but it's a gateway to one of the language's more advanced features: Mixins. Using the spread operator like you have does not perform a "deep" amend, it only replaces the keys in A another: Mixin<Dynamic> = new {
spring {
test {
name = "True"
}
}
} Integrated into your example code, it looks like this: class Config {
spring: SpringConfig
}
class SpringConfig {
world: WorldConfig?
test: TestConfig?
}
class WorldConfig {
name: String
}
class TestConfig {
name: String
}
source: Dynamic = new {
spring {
world {
name = "True"
}
}
field = 1
}
hidden another: Mixin<Dynamic> = new {
spring {
test {
name = "True"
}
}
}
merged = source |> another
mergedOther = (source) {
spring {
test {
name = "True"
}
}
} Which renders the way you were originally expecting: source {
spring {
world {
name = "True"
}
}
field = 1
}
merged {
spring {
world {
name = "True"
}
test {
name = "True"
}
}
field = 1
}
mergedOther {
spring {
world {
name = "True"
}
test {
name = "True"
}
}
field = 1
} The one major pain point I've found with Mixins is that they cannot be directly rendered (since they are "just" functions) and there's no direct or implicit way to mix them into an empty value. You can do this explicitly like this: anotherRendered = new Dynamic {} |> another Which (in the above example) renders to:
Another especially interesting thing about Mixins is that that they themselves can be amended! Adding some more: hidden anotherAgain: Mixin<Dynamic> = (another) { // <- this amends the existing Mixin another!
spring {
test {
variant = "Debug"
}
}
}
mergedAgain = source |> anotherAgain This renders as you might hope:
|
Beta Was this translation helpful? Give feedback.
-
Wow! Awesome! Thanks for quick reply and detailed explanation! |
Beta Was this translation helpful? Give feedback.
I ran across this myself a few weeks ago! Not only is this expected, but it's a gateway to one of the language's more advanced features: Mixins.
Using the spread operator like you have does not perform a "deep" amend, it only replaces the keys in
source
with the keys that exist inanother
, which explains why the output formerged
looks the way it does.A
Mixin<Dynamic>
is sugar forFunction1<Dynamic, Dynamic>
, or a function that accepts aDynamic
, transforms it, and returns the result. Creating a Mixin looks very similar to creating a regular value:Integrated into your example code, it…