Skip to content

GROOVY-12585 + GROOVY-12643 + GROOVY-12644: consistent collection and map conversions - #3165

Merged
paulk-asert merged 3 commits into
apache:masterfrom
paulk-asert:groovy12585
Nov 6, 2026
Merged

paulk-asert merged 3 commits into
apache:masterfrom
paulk-asert:groovy12585

Conversation

@paulk-asert

Copy link
Copy Markdown
Contributor

Summary

Make collection and map conversions consistent between dynamic code, @TypeChecked and @CompileStatic. Three commits, one per JIRA, each with its own tests and COMPATIBILITY entry:

Commit Issue Scope
1 GROOVY-12585 Runtime: one table of default implementations for casting and as
2 GROOVY-12643 Type checker: list and map literals assigned to collection types
3 GROOVY-12644 Type checker: list and map literals returned from methods

1. GROOVY-12585: runtime

Assignment and cast (castToType) and coercion with as (asType) now share one table of default implementations:

Target Default
List, Collection, Iterable ArrayList
Set LinkedHashSet
SortedSet, NavigableSet TreeSet
Queue, Deque LinkedList
BlockingQueue LinkedBlockingQueue
SortedMap, NavigableMap TreeMap
ConcurrentMap ConcurrentHashMap
  • SortedSet s = list, Deque d = list, Stack s = list, List l = aSet, SortedMap m = map and Iterable i = anArray now succeed; they threw GroovyCastException.
  • as NavigableSet, as Deque, as BlockingQueue, as SortedMap, as NavigableMap and as ConcurrentMap return a real collection (a copy) instead of a proxy that did not behave like the type.
  • anArray as Set keeps element order (LinkedHashSet, not HashSet).
  • On assignment, a concrete collection class tries its copy constructor, then its no-arg constructor plus addAll, before passing the elements as constructor arguments. So Vector v = [5], PriorityQueue q = [5] and ArrayDeque d = [5] hold the element instead of being empty with that capacity.
  • Unchanged: as with a concrete class keeps its own path (list as HashSet is a HashSet; HashSet h = list is still a LinkedHashSet). The GROOVY-7867 fallback order and its suppressed exception are also unchanged.

2. GROOVY-12643: type checker, assigned literals

  • A list literal assigned to SortedSet, NavigableSet, Queue, Deque or BlockingQueue, and a map literal assigned to SortedMap, NavigableMap or ConcurrentMap, now compile, as Set already did. These have been compile errors since at least 2.4. The inferred type is the default implementation, and the elements are checked against the declared type arguments.
  • A list literal assigned to a concrete collection class with a collection or no-arg constructor copies the elements instead of passing them as constructor arguments. So LinkedList l = [3, 1] and Stack s = [3, 1] compile, and under @CompileStatic, Vector v = [5] holds the element, as in dynamic code. Other classes keep the list-constructor rule (Point p = [1, 2], Dimension d = [100, 200]).
  • @CompileStatic needs no new code generation: the existing indy cast already goes through castToType.

3. GROOVY-12644: type checker, returned literals

A list or map literal returned from a method was accepted only if the literal's own class was assignable to the return type, so Set m() { [3, 1] } failed although Set s = [3, 1] compiles. A returned literal is now checked as ReturnType x = literal is. This only accepts code that did not compile before. Array return types keep their existing check. Closure and lambda results are unchanged, because they are not converted to the expected type at run time.

Compatibility

Most of this only turns failures into results. The changes in behaviour that reviewers should look at:

  • Proxies become copies: as for the interfaces above returns a copy instead of a proxy over the original collection or map.
  • Element order: anArray as Set keeps it.
  • The capacity idiom (commit 2), the main one to decide: statically compiled code that used a one-element literal as a capacity changes meaning. Vector v = [10] now holds 10, and ArrayDeque<String> d = [16] is a compile error; write new ArrayDeque(16) for a capacity. ArraysAndCollectionsSTCTest pinned ArrayDeque<String> deque = [123] // ArrayDeque(int numElements) from GROOVY-10002, and it now asserts the new behaviour. @eric-milles, does that look right to you?

Each change has an entry in COMPATIBILITY.md. The list and map constructor section of core-semantics.adoc is updated.

Tests

  • New: bugs.Groovy12585, bugs.Groovy12643 and bugs.Groovy12644, 10 tests each. They cover dynamic code, @TypeChecked and @CompileStatic, generics, and negative and unchanged-behaviour cases. Each fails without its commit's production change, except the guards for unchanged behaviour.
  • Updated: ConstructorsSTCTest.testMapLiteral (SortedMap m = [:]), and ArraysAndCollectionsSTCTest (the Deque/Queue literal rejections and the capacity idiom).
  • The full :test suite passes on each commit.

Related

  • GROOVY-12584: Indy cast of a Collection to an abstract subclass of Ha… #3111 (GROOVY-12584) removes the indy cast selector's collection fast path, so every indy collection cast goes through castToType. It is independent of this PR and can land in either order. It closes the one indy-only case where assignment and as still differ: an abstract subclass of HashSet or ArrayList.
  • Out of scope: a list or map argument is not converted to a method's parameter type, in any mode, by design.

…ions for casting and as

Assignment and cast (castToType) and coercion with as (asType) now share
one table of default implementations: ArrayList for List, Collection and
Iterable; LinkedHashSet for Set; TreeSet for SortedSet and NavigableSet;
LinkedList for Queue and Deque; LinkedBlockingQueue for BlockingQueue;
TreeMap for SortedMap and NavigableMap; ConcurrentHashMap for
ConcurrentMap. So assignments such as SortedSet s = list now succeed, and
as returns a real collection for these types instead of a proxy.

On assignment, a concrete collection class tries its copy constructor,
then its no-arg constructor plus addAll, before the elements as
constructor arguments, as as already did. So Vector v = [5] holds the
element instead of being an empty Vector of capacity 5. An array coerced
with as follows the same table, so anArray as Set keeps element order.
…ction types like the runtime cast

Under @TypeChecked and @CompileStatic, a list literal assigned to
SortedSet, NavigableSet, Queue, Deque or BlockingQueue, and a map literal
assigned to SortedMap, NavigableMap or ConcurrentMap, now compile, as Set
already did. The inferred type is the default implementation the runtime
cast creates (GROOVY-12585), and the elements are checked against the
declared type arguments.

A list literal assigned to a concrete collection class with a constructor
taking a collection, or a no-arg constructor, now copies the elements
instead of passing them as constructor arguments. So LinkedList l = [3, 1]
compiles, and under @CompileStatic Vector v = [5] holds the element rather
than being empty with capacity 5, matching dynamic code. Using a literal
to set a capacity, as in ArrayDeque<String> d = [16], is now an error.
Other classes, such as Dimension, keep the list-constructor rule.
…ethod like an assigned one

Under @TypeChecked and @CompileStatic, a list or map literal returned from
a method with a declared return type was accepted only when the literal's
own class (ArrayList or LinkedHashMap) is assignable to the return type, so
Set m() { [3, 1] } and TreeMap m() { [b: 2, a: 1] } failed although the
same literal assigned to a variable of that type compiles.

A returned literal is now checked as "ReturnType x = literal" is: the Set
exemption, the interface defaults and copy rule (GROOVY-12643) and the
list and map constructor shorthand apply, and the elements are checked
against the declared type arguments. Array return types keep their
existing check. Closure and lambda results are unchanged, since they are
not converted to the expected type at run time.
@codecov-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.70833% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 74.1730%. Comparing base (4603713) to head (fd35106).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
...roovy/transform/stc/StaticTypeCheckingVisitor.java 93.7500% 0 Missing and 3 partials ⚠️
.../codehaus/groovy/runtime/DefaultGroovyMethods.java 66.6667% 1 Missing and 1 partial ⚠️
...untime/typehandling/DefaultTypeTransformation.java 95.2381% 0 Missing and 2 partials ⚠️
Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                 @@
##               master      #3165        +/-   ##
==================================================
+ Coverage     74.1568%   74.1730%   +0.0163%     
- Complexity      43757      43792        +35     
==================================================
  Files            1692       1692                
  Lines          149517     149584        +67     
  Branches        28366      28383        +17     
==================================================
+ Hits           110877     110951        +74     
+ Misses          28446      28440         -6     
+ Partials        10194      10193         -1     
Files with missing lines Coverage Δ
...rg/codehaus/groovy/runtime/ArrayGroovyMethods.java 87.3918% <ø> (+0.0671%) ⬆️
.../codehaus/groovy/runtime/DefaultGroovyMethods.java 75.7645% <66.6667%> (+0.0401%) ⬆️
...untime/typehandling/DefaultTypeTransformation.java 66.6667% <95.2381%> (+1.7812%) ⬆️
...roovy/transform/stc/StaticTypeCheckingVisitor.java 88.2452% <93.7500%> (+0.0273%) ⬆️

... and 18 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@testlens-app

testlens-app Bot commented Nov 2, 2026

Copy link
Copy Markdown

✅ All tests passed ✅

🏷️ Commit: fd35106
▶️ Tests: 127630 executed
⚪️ Checks: 27/27 completed


Learn more about TestLens at testlens.app/docs.

@paulk-asert paulk-asert changed the title GROOVY-12585 + GROOVY-12643 + GROOVY-12644 GROOVY-12585 + GROOVY-12643 + GROOVY-12644: consistent collection and map conversions Nov 5, 2026
@paulk-asert
paulk-asert merged commit 0bb11cd into apache:master Nov 6, 2026
28 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants