Copilot commented on code in PR #2641:
URL: https://github.com/apache/groovy/pull/2641#discussion_r3489911417
##########
src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java:
##########
@@ -19155,6 +19155,61 @@ public static <K, V> Map<K, V> withDefault(Map<K, V>
self, boolean autoGrow, boo
return MapWithDefault.newInstance(self, autoGrow, autoShrink, init);
}
+ /**
+ * Decorates the given Map with a default value supplied by a closure, as
per
+ * {@link #withDefault(Map, Closure)}, but the returned map additionally
enforces its
+ * key and value types at runtime. Looking up (and so auto-growing for) a
key that is
+ * not an instance of {@code keyType} throws {@link ClassCastException} at
the point of
+ * misuse, rather than silently inserting a wrong-typed key that only
surfaces later
+ * (for example when reading {@code keySet()}). The check is provided by
decorating an
+ * {@link #asChecked(Map, Class, Class) asChecked} view, so direct
mutation such as
+ * {@code map[key] = value} is guarded too.
+ * <pre class="language-groovy">
+ * def m = [:].withDefault(Number, Object){ 42 }
+ * assert m[1] == 42 // a compatible key grows the map
+ * // m['x'] // would throw ClassCastException
(incompatible key)
+ * </pre>
Review Comment:
The GroovyDoc example for the key+value checked overload uses `Object` as
`valueType`, which effectively disables value checking and undermines the
method’s stated purpose (runtime enforcement of both key and value types).
Using a concrete `valueType` (e.g. `String`) and showing an incompatible value
case would make the example accurate and less confusing.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]