Iterable and valhalla
Jens Lideström
jens.lidestrom at fripost.org
Sat Jul 23 14:51:13 UTC 2022
This kind of cursor class is an interesting application of value classes. They have been discussed on the mailing lists previously and are also used as an example in the State of Valhalla document:
https://github.com/openjdk/valhalla-docs/blob/100f007ceba1beae11d9bdb7eef017b0f7d980e9/site/design-notes/state-of-valhalla/02-object-model.md#value-classes-separating-references-from-identity
Mutable iterators in C# is an interesting application of mutable value classes.
It would be interesting to dig up the initial design discussion about mutable contra immutable value classes in the mailing list archives. It's too bad that Pipermail archives are so hard to search...
BR,
Jens Lideström
On 2022-07-22 00:00, Robbe Pincket wrote:
> 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
>
More information about the valhalla-spec-observers
mailing list