Exercise: Operator Overloads for Json Manipulation
This will be yet another problem involving json (What can I say? I'm a web developer and it's kind of relevant to web development.), but to mix things up, we'll work with the Vertx library's JsonObject and JsonArray this time. So you'll want to add these two dependencies to your build.gradle file:compile group: 'io.vertx', name: 'vertx-core', version: '3.8.0' compile group: 'io.vertx', name: 'vertx-lang-kotlin', version: '3.8.0'From here there are two paths that can be explored: one where the operator overloads that we write treat the JsonObject or JsonArray as immutable, and the other where the operator overloads that we write treat the JsonObject or JsonArray as mutable. Note that these two approaches don't play well together, and should be explored separately.
Immutable
In the immutable scenario, we'll want to overload the plus and minus operators for both JsonObject and JsonArray. In all cases the JsonObjects and/or JsonArrays won't be modified, but a new one will be created and returned instead. When adding two JsonObjects together, the fields from both JsonObjects will be added to the new JsonObject. When there are overlapping fields, the fields from the latter JsonObject will take precedence. When a JsonObject and a Pair are added together, then the Pair is added as a field on the JsonObject, or replaces an existing field if there's overlap. Subtracting a String from a JsonObject will subtract the field with that key from the JsonObject. Subtracting a Collection of Strings from a JsonObject will remove all fields that have a corresponding key.Adding two JsonArrays should return a JsonArray with all the values from both JsonArrays, with the values from the former JsonArray being first and the values from the latter JsonArray being last. Adding any object to the JsonArray will append that object to the end of the JsonArray. Subtracting any object from a JsonArray will remove the firstinstance of that object from the JsonArray. Subtracting one JsonArray from another will remove all of the values in the second JsonArray from the first JsonArray. Something to explore would be whether or not it would be meaningful to implement the operator such that subtracting an int from a JsonArray will remove the element at that index.
Mutable
This should follow the same general rules as defined by the immutable problem above except that it will modify the first JsonObject or JsonArray. This will implement the += and -= operators directly, and not implement the + or - operators.As usual, a solution will be posted in a followup update. And here's the answers.