Copilot commented on code in PR #2553:
URL: https://github.com/apache/groovy/pull/2553#discussion_r3291070512


##########
src/main/java/org/codehaus/groovy/runtime/DefaultGroovyMethods.java:
##########
@@ -15068,6 +15068,33 @@ public void remove() {
         }
     }
 
+    
//--------------------------------------------------------------------------
+    // takeIf
+
+    /**
+     * Returns this object if it satisfies the given predicate, or {@code null}
+     * otherwise. Useful for guarding a value through a chain, particularly 
with
+     * the Elvis or safe-navigation operators.
+     * <pre class="language-groovy groovyTestCase">
+     * assert 'hello'.takeIf{ it.startsWith('h') } == 'hello'
+     * assert 'hello'.takeIf{ it.startsWith('z') } == null
+     * assert ('input'.takeIf{ it.startsWith('http') } ?: "https://input";) == 
'https://input'
+     * assert [1, 2, 3].takeIf{ !it.isEmpty() }?.size() == 3
+     * assert [].takeIf{ !it.isEmpty() }?.size() == null
+     * </pre>
+     * The predicate is invoked with the receiver as its argument; the receiver
+     * is not used as a delegate. The receiver is passed through to the 
predicate
+     * unchanged, including when it is {@code null}.
+     *
+     * @param self      the object to test
+     * @param condition the predicate applied to {@code self}
+     * @return {@code self} if {@code condition.test(self)} is {@code true}, 
otherwise {@code null}
+     * @since 6.0.0
+     */
+    public static <T> T takeIf(T self, Predicate<T> condition) {
+        return condition.test(self) ? self : null;

Review Comment:
   The parameter type `Predicate<T>` is unnecessarily invariant for a 
general-purpose GDK method. Using `Predicate<? super T>` makes the API more 
flexible (e.g., allows a `Predicate<Object>` to be used when `T` is a subtype) 
without changing behavior.
   



-- 
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]

Reply via email to