Copilot commented on code in PR #2752:
URL: https://github.com/apache/groovy/pull/2752#discussion_r3682276449
##########
src/main/java/org/codehaus/groovy/runtime/ArrayGroovyMethods.java:
##########
@@ -997,6 +1137,29 @@ public static <K, V, E> Map<K, V> collectEntries(E[]
self, Map<K, V> collector,
return DefaultGroovyMethods.collectEntries(new ArrayIterator<>(self),
collector, transform);
}
+ /**
+ * Iterates through an array transforming each element into a map entry
using the
+ * transform function and adding it to the collector. A "fat-free" variant
of
+ * {@link #collectEntries(Object[], Map, Closure)} accepting a {@link
Function}.
+ * <pre class="language-groovy groovyTestCase">
+ * String[] words = ['bb', 'ccc']
+ * assert words.collectEntries([a: 1], w -> new MapEntry(w, w.size()))
== [a: 1, bb: 2, ccc: 3]
+ * </pre>
+ *
+ * @param self an array
+ * @param collector an initial map to add the collected entries to
+ * @param transform the transform function applied to each element,
returning a map entry
+ * @return the collector with the collected entries added to it
+ * @since 6.0.0
+ */
+ public static <K, V, E> Map<K, V> collectEntries(E[] self, Map<K, V>
collector, Function<? super E, ? extends Map.Entry<K, V>> transform) {
+ for (E item : self) {
+ Map.Entry<K, V> entry = transform.apply(item);
+ collector.put(entry.getKey(), entry.getValue());
+ }
+ return collector;
+ }
Review Comment:
`collectEntries(E[] self, Map collector, Function transform)` currently
dereferences `entry.getKey()/getValue()` unconditionally. If the transform
returns `null`, this will throw an NPE, whereas
`DefaultGroovyMethods.collectEntries(..., Closure)` (via `addEntry`) treats a
`null` entrySpec as “insert nothing” (see GROOVY-10893 handling). The array
overload should mirror that behavior by skipping null entries.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]