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

Generated toList() and toMap() methods on records perform unnecessary wrapping

    XMLWordPrintableJSON

Details

    • Bug
    • Status: Closed
    • Minor
    • Resolution: Fixed
    • 4.0.17
    • 4.0.19, 5.0.0-alpha-6
    • None
    • None

    Description

      I have the following code:

      import groovy.transform.CompileStatic
      
      @CompileStatic
      static void main(String[] args) {
          println(new Person("John", 42).size())
      }
      
      @CompileStatic
      record Person(String name, int age) {} 
      

      When checking the compiled output, the toList and toMap methods appear to call a helper method to create a mutable list and map, respectively. These are then wrapped inside another ArrayList/LinkedHashMap:

      @Generated
      public final List toList() {
          return new ArrayList(ScriptBytecodeAdapter.createList(new Object[]{this.name(), this.age()}));
      }
      
      @Generated
      public final Map toMap() {
          return new LinkedHashMap(ScriptBytecodeAdapter.createMap(new Object[]{"name", this.name(), "age", this.age()}));
      }
      

      This wrapping is unnecessary.

      Sidenote: Should these return mutable collections considering records are expected to be heavily immutable? If not, might be worth considering changing them to immutable in Groovy 5, something along the lines of:

      @Generated
      public final List toList() {
          return List.of(new Object[]{this.name(), this.age()});
      }
      
      @Generated
      public final Map toMap() {
          return Map.of(new Object[]{"name", this.name(), "age", this.age()});
      }
      

      Attachments

        Activity

          People

            paulk Paul King
            paint_ninja Oscar N
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: