Uploaded image for project: 'Groovy'
  1. Groovy
  2. GROOVY-10508

DefaultGroovyMethods.get() unexpectedly puts the default value into the origin map

    XMLWordPrintableJSON

Details

    • Documentation
    • Status: Closed
    • Minor
    • Resolution: Fixed
    • None
    • 4.0.1
    • None
    • None

    Description

       

      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);
      } 

      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,

       

      RMapCache<String, String> map = redissonClient.getMapCache(SOME_KEY)
      String cachedValue = map.getOrDefault(key, null) 

      it will return a NullPointerError like "map value can't be null".

       

      Attachments

        Activity

          People

            paulk Paul King
            Stallone Shi Tailong
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: