[ 
https://issues.apache.org/jira/browse/GROOVY-12031?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=18082972#comment-18082972
 ] 

ASF GitHub Bot commented on GROOVY-12031:
-----------------------------------------

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.
   





> Provide a DGM#takeIf method
> ---------------------------
>
>                 Key: GROOVY-12031
>                 URL: https://issues.apache.org/jira/browse/GROOVY-12031
>             Project: Groovy
>          Issue Type: New Feature
>            Reporter: Paul King
>            Assignee: Paul King
>            Priority: Major
>
> Matching Kotlin's method of the same name.



--
This message was sent by Atlassian Jira
(v8.20.10#820010)

Reply via email to