Iterable and valhalla
Robbe Pincket
robbepincket at live.be
Thu Jul 21 22:00:18 UTC 2022
Hello all
I was recently thinking about cases where the new "value classes"/"primitive classes" (or whatever they'll be called) can be used. One of the common places where I learned C# devs use their structs, back when I used to code in C#, is in iterators. However, this is not a case we can mirror in Java, as our version of these "structs" are immutable. However there are variants that could still allow these, and I was wondering whether any thought has been given to those (or other variants) yet, and/or whether they are deemed not useful.
One such variation:
```java
class ArrayList<T> implements Iterable2<T> {
@Override
public Iterator2<T> iterator2() {
return new ArrayListCursor<>(this, 0);
}
value record ArrayListCursor<T>(ArrayList<T> list, int index) implements Iterator2<T> {
@Override
public boolean hasNext() {
return index < list.size();
}
@Override
public Tupple2<T, Iterator2<T>> moveNext() {
if (!this.hasNext()) {
throw new NoSuchElementException();
}
return new Tupple2(list.get(index), new ArrayListCursor<>(list, index + 1));
}
// or
@Override
public T next() {
if (!this.hasNext()) {
throw new NoSuchElementException();
}
return list.get(index);
}
@Override
Iterator2<T> moveNext() {
if (!this.hasNext()) {
throw new NoSuchElementException();
}
return new ArrayListCursor<>(list, index + 1);
}
}
}
```
Greetings
Robbe Pincket
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/valhalla-spec-observers/attachments/20220721/7b067f55/attachment-0001.htm>
More information about the valhalla-spec-observers
mailing list