In .NET you have Ducktyped foreach stuff. This means that you don't need to implement IEnumerable to be usable with foreach statements: public class MyCollection { int[] items; public MyCollection() { items = new int[5] {12, 44, 33, 2, 50}; } public MyEnumerator GetEnumerator() { return new MyEnumerator(this); } public class MyEnumerator { int nIndex; MyCollection collection; public MyEnumerator(MyCollection coll) { collection = coll; nIndex = -1; } public bool MoveNext() { nIndex++; return(nIndex < collection.items.GetLength(0)); } public int Current { get { return(collection.items[nIndex]); } } } } public class MainClass { public static void Main() { MyCollection col = new MyCollection(); Console.WriteLine("Values in the collection are:"); foreach (int i in col) Console.WriteLine(i); } } I figured that we can have this in Vala too. The instance being iterated must only have the possibility to return an iterator. Although a Gee.Iteratable ensures this in a type safe way, any instance with a get_iterator method should be usable for the vala.ForeachStatement This might make it possible to have funny types that are not really iteratable yet can provide a get_iterator. For example non-list types that still allow a foreach: Person p = .. foreach (Arm a in p) { a.Wave (); } The added benefit for this type is that if we ever inherit a type from Person, say a PersonWithFiveArms then that inherited version must just override the get_iterator, yet don't become "like a list type". It's probably too rare indeed, but experimenting with Jürg's excellent Vala code is too fun, sorry. Here's a first pseudo-code-something patch that I need to convert to something that would compile and work. Am I looking in the right direction for this? Else just put on me on the right track on IRC or something, or reply here :) -- Philip Van Hoof, software developer home: me at pvanhoof dot be gnome: pvanhoof at gnome dot org http://www.pvanhoof.be/blog
Attachment:
ducktype_foreach.diff
Description: Text Data