This is something I stumbled on recently when trying to implement javax.jcr.NodeIterator in Scala.
Assume you are using a library which exports an Iterator2 interface:
public interface Iterator2 extends java.util.Iterator {}
Note that Iterator is a raw type and Iterator2 does not take any type parameters. So how would you implement Iterator2 in Scala?
Here is a start:
class MyIterator extends Iterator2 { def hasNext = false def remove = throw new Error def next: Nothing = throw new Error }
But if the next method should return an actual value, what would be it’s return type? It turn’s out that any other type than Nothing results in a compiler error:
error overriding method next in trait Iterator of type ()E; method next has incompatible type ()Any
So how would you implement Iterator2?
Advertisements
Scala does not understand raw types. You must implement MyIterator in Java. See: http://lampsvn.epfl.ch/trac/scala/ticket/1737
Oh, I wasn’t aware of that. Thanks for pointing me to the ticket.
So I probably found a workaround? Hmm or probably my workaround has limitations I cannot see yet 😉 Anyway, I’ll post it in a couple of days.
There’s no perfect answer. One answer is to write an abstract Java class that implements all the raw methods in terms of Object based methods
public abstract class UnRawIterator implements Iterator2 {
public abstract Object unRawNext();
final public Object next() { return unRawNext();}
}
Now we can write Scala
class MyIterator extends UnRawIterator {
def unRawNext = “hello”
def hasNext = true
def remove = error(“no can doo”)
}
It’s seriously ugly. I think there’s a long standing trac issue around this.
What’s “seriously ugly” about this is the fact that Java *allows* the use of raw types as in the example. Scala, having a safer and more consistent type system, doesn’t have any way of reasonably processing an override like the example.
If you can think of a sound solution to this problem, I’m willing to be that the compiler folks are open to suggestions.
[…] I wasn’t aware of Ticket #1737 when I was trying to find a solution to the problem from my previous post. Thanks to Jorge Ortiz for pointing this out. However, I reviewed my approach to solving this and […]
[…] Java Interfaces and Generics 30 08 2009 In an earlier post I asked for an implementation of the following Java interface in […]
plz suggest me how implement puzzle in java