Skip to content

Commit

Permalink
GROOVY-11308: Restore compatibility of Collection#unique
Browse files Browse the repository at this point in the history
The documentation for this method states that when `mutate` is false, a new collection is _always_ returned. The previous code only did so when self.size() was greater than 1, and otherwise returned null.
  • Loading branch information
octylFractal authored and paulk-asert committed Feb 14, 2024
1 parent 4725c43 commit a43d5d4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14580,10 +14580,7 @@ public static <T> List<T> unique(List<T> self) {
* @since 1.8.1
*/
public static <T> Collection<T> unique(Collection<T> self, boolean mutate) {
Collection<T> answer = null;
if (mutate || (self != null && self.size() > 1)) {
answer = uniqueItems(self);
}
Collection<T> answer = uniqueItems(self);
if (mutate) {
self.clear();
self.addAll(answer);
Expand Down
18 changes: 18 additions & 0 deletions src/test/groovy/UniqueOnCollectionTest.groovy
Original file line number Diff line number Diff line change
Expand Up @@ -112,4 +112,22 @@ class UniqueOnCollectionTest extends GroovyTestCase {
assert orig == [1, 3, 2, 3]
assert uniq == [1, 3, 2]
}

/** GROOVY-11308 */
void testNonMutatingEmpty() {
def it = []
def uniq = it.unique( false )
assert uniq !== it : "Must be a different instance to preserve documented behavior"
assert uniq == []
assert it == []
}

/** GROOVY-11308 */
void testNonMutatingSingleElement() {
def it = [1]
def uniq = it.unique( false )
assert uniq !== it : "Must be a different instance to preserve documented behavior"
assert uniq == [1]
assert it == [1]
}
}

0 comments on commit a43d5d4

Please sign in to comment.