[ 
https://issues.apache.org/jira/browse/GROOVY-11807?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=18092261#comment-18092261
 ] 

ASF GitHub Bot commented on GROOVY-11807:
-----------------------------------------

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.





> MapWithDefault can break type safety of key set
> -----------------------------------------------
>
>                 Key: GROOVY-11807
>                 URL: https://issues.apache.org/jira/browse/GROOVY-11807
>             Project: Groovy
>          Issue Type: Bug
>          Components: groovy-jdk
>            Reporter: Eric Milles
>            Assignee: Paul King
>            Priority: Major
>
> {code}
> Map<Number,?> map = [:].withDefault{ null }
> assert map.get('x') == null
> Number k = map.keySet()[0]
> {code}
> GroovyCastException: Cannot cast object 'x' with class 'java.lang.String' to 
> class 'java.lang.Number'



--
This message was sent by Atlassian Jira
(v8.20.10#820010)

Reply via email to