M. Justin created GROOVY-10944:
----------------------------------
Summary: Inconsistency with getAt between List and other Iterables
Key: GROOVY-10944
URL: https://issues.apache.org/jira/browse/GROOVY-10944
Project: Groovy
Issue Type: Bug
Components: groovy-jdk
Affects Versions: 4.0.9
Reporter: M. Justin
I noticed a difference in behavior between how {{getAt(int index)}} functions
for {{List}} and other implementations of {{{}Iterable{}}}. Namely,
non-{{{}List{}}} {{{}Iterable{}}}s will return {{null}} for negative values
outside of the range of items, whereas {{List}} will throw
{{{}ArrayIndexOutOfBoundsException{}}}.
{{def tryPrint(Iterable o, int index) {}}
{{ try {}}
{{ println(o[index])}}
{{ } catch (Exception e) {}}
{{ println(e.getClass().simpleName)}}
{{ }}}
{{}}}
{{List<String> strings = ['A', 'B', 'C']}}
{{tryPrint(strings as Set, -4) // null}}
{{tryPrint(strings as List, -4) // ArrayIndexOutOfBoundsException}}
{{tryPrint(Collections.unmodifiableCollection(strings), -4) // null}}
The documentation for {{Iterable.getAt}} seems to indicate that null should be
returned if there value is out of range (there is "no corresponding value"):
{quote}*Returns:*
the value at the given index (after normalisation) or null if no corresponding
value was found
{quote}
The documentation for List.getAt makes no such claims:
{quote}{*}Returns:{*}the value at the given index
{quote}
It seems undesirable for the subclass method to throw an exception where the
superclass method does not. It seems extra undesirable given that the
difference is not documented.
Note that both {{List}} and non-{{{}List{}}} {{{}Iterable{}}}s will return
{{null}} for positive values outside of the range of items:
{{tryPrint(strings as Set, 4) // null}}
{{tryPrint(strings as List, 4) // null}}
{{tryPrint(Collections.unmodifiableCollection(strings), 4) // null}}
h2. Expected behavior:
I would expect consistent behavior between {{List}} and non-{{{}List{}}}
{{{}Iterable{}}}s with regard to this method, given that there's nothing
special about {{List}} that would appear to warrant this difference.
It feels like both should return {{null}} when the index is out of range
(positive or negative). But having both throw the exception in that case would
be reasonable, if less convenient.
h2. Similar past issues:
There are two "won't fix" issues regarding the inconsistency between positive
and negative out-of-bounds behavior of {{{}List{}}}:
* GROOVY-1286
* GROOVY-4652
However, these were concerned with the inconsistency within {{List}} itself.
As this ticket involves the inconsistency between {{List}} and non-{{{}List{}}}
{{{}Iterable{}}}s, and not the between positive/negative index behavior, I
would argue it's a different problem than these two existing issues.
--
This message was sent by Atlassian Jira
(v8.20.10#820010)