You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@groovy.apache.org by "Paul King (Jira)" <ji...@apache.org> on 2022/02/24 12:03:00 UTC

[jira] [Commented] (GROOVY-10508) DefaultGroovyMethods.get() should not put the default value into the origin map

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

Paul King commented on GROOVY-10508:
------------------------------------

I agree with you that if we were designing that method these days we would have probably done it differently. Looking at the history of this however, it was added in 2004 before Groovy 1.0, so it would be a breaking change for long standing behavior which is documented correctly. We could consider such a change but my suggestion would be to simply avoid that method if you think any future confusion for readers of your code might arise. Instead, either:
* If you want that behavior, use the {{MapWithDefault}} class
* If not, use Java 8's {{Map#getOrDefault(key, defaultValue)}}

Even for {{MapWithDefault}} there has been discussion about whether the default value should be stored. See GROOVY-7802. We could progress that too as a possibility but with the {{Map#getOrDefault}} method available, there is perhaps less need.

> DefaultGroovyMethods.get() should not put the default value into the origin map
> -------------------------------------------------------------------------------
>
>                 Key: GROOVY-10508
>                 URL: https://issues.apache.org/jira/browse/GROOVY-10508
>             Project: Groovy
>          Issue Type: Improvement
>            Reporter: Shi Tailong
>            Priority: Minor
>
>  
> {code:java}
> public static <K, V> V get(Map<K, V> map, K key, V defaultValue) {
>     if (!map.containsKey(key)) {
>         map.put(key, defaultValue);
>     }
>     return map.get(key);
> } {code}
> Above there's the get() method for ALL maps if there's more than one arguments for this. You can find that it will put the defaultValue into the map if the key doesn't hit.
>  
> It seems not to be an obvious choice for programmers, as the origin map would be CHANGED when the programmer may just want a default value.
> Meanwhile, some of the implements of Map have some restrictions for the values. For example, Redisson doesn't allow null values for its RMap class. So when you're using Redisson in Groovy like this,
>  
> {code:java}
> RMapCache<String, String> map = redissonClient.getMapCache(SOME_KEY)
> String cachedValue = map.getOrDefault(key, null) {code}
> it will return a NullPointerError like "map value can't be null".
>  



--
This message was sent by Atlassian Jira
(v8.20.1#820001)