Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Note: This PR is a draft as I evaluate the best design in terms of user-friendliness, simplicity and performance.
Issue to be solved
In many instances, JsonObjects and arrays are structured in a uniform way, so that we know that a JsonArray contains only JsonObjects, for example.
This however poses a challenge when iterating: The type bound for
JsonObject
andJsonArray
isObject
, so every Object has to be iterated and then cast manually, leading to much clutter in client code.The Solution
Add Helper methods to
JsonArray
andJsonObject
that resembe theforEach()
method, but accepting a (Bi-)Consumer of the desired type. Only elements whose type matches the wanted type are handed on to the Consumers in order to preventClassCastException
s.Alternatives
The alternative I Use uses unchecked casting and then iteration, something akin to
but this also erases type safety, potentially leading to unexpected
ClassCastException
s, furthermore we loose all array specific methods if we don't sacrifice an extra line of code for an intermediate variable.Risks and Assumptions
The main risk lies in the user maybe not expecting not to consume all elements in the case of incompatible objects found. These users, however, can always fall back to the standard List/Map
forEach()
methods.