Permalink
Browse files

GROOVY-5745: DGM should have a getAt method for Iterable

  • Loading branch information...
1 parent c215e5d commit 78988fed1e2be1bfc64c7e1dd1c74edd9b11ea3a @paulk-asert paulk-asert committed Oct 6, 2012
Showing with 25 additions and 0 deletions.
  1. +25 −0 src/main/org/codehaus/groovy/runtime/DefaultGroovyMethods.java
@@ -5128,6 +5128,31 @@ public static int size(Object[] self) {
return null;
}
+
+ /**
+ * Support the subscript operator for an Iterable. Typical usage:
+ * <pre class="groovyTestCase">
+ * // custom Iterable example:
+ * class MyIterable implements Iterable {
+ * Iterator iterator() { [1, 2, 3].iterator() }
+ * }
+ * def myIterable = new MyIterable()
+ * assert myIterable[1] == 2
+ *
+ * // Set example:
+ * def set = [1,2,3] as HashSet
+ * assert set[1] == 2
+ * </pre>
+ *
+ * @param self an Iterable
+ * @param idx an index value (-self.size() <= idx < self.size()) but using -ve index values will be inefficient
+ * @return the value at the given index (after normalisation) or null if no corresponding value was found
+ * @since 2.1.0
+ */
+ public static <T> T getAt(Iterable<T> self, int idx) {
+ return getAt(self.iterator(), idx);
+ }
+
/**
* A helper method to allow lists to work with subscript operators.
* <pre class="groovyTestCase">def list = [2, 3]

0 comments on commit 78988fe

Please sign in to comment.