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

Jochen Theodorou commented on GROOVY-11807:
-------------------------------------------

I don't think there is really a solution to this unless we get the compiler to 
actually change the call from withDefault(Closure) to withDefault(Class, 
Closure) and then checking those classes against the actual intend and allow 
grow only if the given class is compatible with the get values class. Let us 
assume we had a Annotation
{code:Java}
    @OverrideCall(1)
    public static <K, V> Map<K, V> withDefault(Map<K, V> self, Class<K> 
keyTypeRef, @ClosureParams(FirstParam.FirstGenericType.class) Closure<V> init) {
        ...
    }
{code}
Telling the static compile to compile 
[:].withDefault{ null }
as
withDefault(map, Number.class, { null }
dynamic Groovy would ignore this and use the overload with the old signature.

This would require changes to the way methods are selected in static mode and 
how they are indexed in dynamic mode.

But then we could have a variant that actually checks the key type and only 
grows the map with a compatible key.

> 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
>            Reporter: Eric Milles
>            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