My fun with IKVM.NET continues this week as I utilize Weka from .NET (just a fun note, but the .NET-compiled version is insanely faster than the Java version doing the exact same thing; suck on that, Java fans!). For the most part, everything has been swell. The hardest part is trying to decipher research methodologies to replicate the systems they describe. Still, I’ve run into a few snags when working with the .NET versions of Weka, the first of which is that you can’t foreach over a Java Enumeration. For example, consider the following:
While it isn’t a huge difference, being able to use foreach would obviously be simpler than having to create an instance of Enumeration, then use it to step through the items. Fortunately, it’s quite easy to generically bridge the gap so that any Enumeration can be enumerated by simply calling an extension method, like so:
How does this work? First, we need to apply the adapter pattern to convert a Java Enumeration into a .NET IEnumerator. Here’s our adapter:
Next, we just need to write the extension method that utilizes our adapter to create an IEnumerable:
And like magic, you can now foreach over any Java Enumeration just like it was a .NET IEnumerable implementor. It’d be nice if this were baked in to IKVM.NET, but for now, this simple "hack" will do the trick.