Oscar N created GROOVY-11285:
--------------------------------
Summary: Generated toList() and toMap() methods on records perform
unnecessary wrapping
Key: GROOVY-11285
URL: https://issues.apache.org/jira/browse/GROOVY-11285
Project: Groovy
Issue Type: Bug
Affects Versions: 4.0.17
Reporter: Oscar N
I have the following code:
{code:groovy}
import groovy.transform.CompileStatic
@CompileStatic
static void main(String[] args) {
println(new Person("John", 42).size())
}
@CompileStatic
record Person(String name, int age) {}
{code}
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:
{code:java}
@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()}));
}
{code}
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:
{code:java}
@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()});
}
{code}
--
This message was sent by Atlassian Jira
(v8.20.10#820010)