You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@groovy.apache.org by "Paul King (Jira)" <ji...@apache.org> on 2021/12/01 01:25:00 UTC

[jira] [Comment Edited] (GROOVY-7207) every() from DefaultGroovyMethods returns true for empty iterator/list

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

Paul King edited comment on GROOVY-7207 at 12/1/21, 1:24 AM:
-------------------------------------------------------------

The {{every}} method fails if it finds a single element in the list which doesn't pass the predicate. Since it can never find such an element for an empty list it will return true. This is consistent with how other languages treat this case:
{code}
Java: emptyStream.allMatch(x -> false) // => true
Kotlin: emptyList.all { false } // => true
Scala: List[String]().forall(x => false) // => true
Ruby: [].all? { |s| false } // => true
{code}


was (Author: paulk):
It would be worth checking what other languages do here but the current implementation assumes {{every}} should fail if it finds a single element in the list which doesn't pass the predicate.

> every() from DefaultGroovyMethods returns true for empty iterator/list
> ----------------------------------------------------------------------
>
>                 Key: GROOVY-7207
>                 URL: https://issues.apache.org/jira/browse/GROOVY-7207
>             Project: Groovy
>          Issue Type: Bug
>          Components: groovy-jdk
>    Affects Versions: 2.3.8, 2.4.0-beta-4
>            Reporter: Dhiraj Mahapatro
>            Priority: Major
>
> {code:java}
> assert [].every()
> assert [].every { it }
> assert [].every { it > 1 }
> {code}
> Is this an expected behavior? In all the variants of {{every()}} in {{DefaultGroovyMethods}} the logic is simlar to
> {code:java}
> BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
> for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {
>     if (!bcw.call(iter.next())) {
>         return false;
>     }
> }
> return true;
> {code}
> So it defaults to true if {{!iter.hasNext()}}. Is this acceptable? Shouldn't it falsify based on empty List fails Groovy Truth?



--
This message was sent by Atlassian Jira
(v8.20.1#820001)