3 ms·
Does that matter for Iterator? You can have class FooIterator implements Iterator<Foo>{…} class BarIterator implements Iterator<Bar>{…} class MyCol
by Someone 2y ago
Does that matter for Iterator? You can have
class FooIterator implements Iterator<Foo>{…}
class BarIterator implements Iterator<Bar>{…}
class MyCollection {
public Iterator<Foo> foos { return new FooIterator(this); };
public Iterator<Foo> bars { return new BarIterator(this); };
}
It would matter for Iterable. You cannot have this:
class MyCollection implements Iterable<Foo>, Iterable<Bar>{…}
, but there, there’s a second problem: in Java, you can’t have overloads that only differ in their return type.
- comex 2y agoIt's not useful to have a type implement Iterator for multiple element types. But in Rust, if Iterator took the element type as a generic parameter, it would be possible. The fact that it's not useful is precisely why Rust makes the element type an associated type instead. The benefits of using an associated type (compared to using a generic parameter in Rust, not compared to Java) include clarity, possibly improving type inference, and avoiding issues with crate coherence by requiring that the Iterator impl live in the crate that defines the input type, rather than the one that defines the output type.