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 2016/10/05 23:26:21 UTC

[jira] [Commented] (GROOVY-7960) IntRange iterator returns null instead of NoSuchElementException

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

Paul King commented on GROOVY-7960:
-----------------------------------

I am happy for this change, but for completeness I think we need to document an edge case that will break after this change. I think it represents a style which we'd discourage but I don't know if someone intended it at some point or perhaps people might have used it by accident. In any case I don't think it would be in wide-spread use and I think documenting it here should suffice.

Before this change the following code works without exception:
{code}
def items = (3..5).iterator()
def x
while (x = items.next()) { println x }
{code}
It silently falls out of the loop once the null is returned. This differs from most other similar collection types, e.g.:
{code}
def items = [3, 4, 5].iterator()
def x
while (x = items.next()) { println x }
{code}
would throw the {{NoSuchElementException}} as the new behavior will now do.

Of course the preferred approach would be to use {{each}} or if the external iterator approach is really required, something like:
{code}
while(items.hasNext()) { println items.next() }
{code}

> IntRange iterator returns null instead of NoSuchElementException
> ----------------------------------------------------------------
>
>                 Key: GROOVY-7960
>                 URL: https://issues.apache.org/jira/browse/GROOVY-7960
>             Project: Groovy
>          Issue Type: Bug
>    Affects Versions: 2.4.7
>            Reporter: John Wagenleitner
>            Assignee: John Wagenleitner
>            Priority: Minor
>              Labels: breaking
>
> Calling {{next()}} on an {{IntRange}} iterator returns {{null}} when {{hasNext{}}} returns false.  As stated in a comment in the class, it should throw {{NoSuchElementException}} to adhere to the Iterator contract.
> {code}
> class IntRangeItrTest extends GroovyTestCase {
>     void testItr() {
>         def itr = (1..2).iterator()        
>         assert itr.next() == 1
>         assert itr.next() == 2
>         assert !itr.hasNext()        
>         shouldFail(NoSuchElementException) {
>             itr.next() // null
>         }
>     }
> }
> {code}



--
This message was sent by Atlassian JIRA
(v6.3.4#6332)