views:

98

answers:

2

I've written a custom trait which extends Iterator[A] and I'd like to be able to use the methods I've written on an Iterator[A] which is returned from another method. Is this possible?

trait Increment[+A] extends Iterator[A]{
    def foo() = "something"
}

class Bar( source:BufferedSource){
    //this ain't working
    def getContents():Increment[+A] = source getLines
}

I'm still trying to get my head around the whole implicits thing and not having much like writing a method in the Bar object definition. How would I go about wrapping such an item to work in the way I'd like above?

+2  A: 

I don't think that this is possible without playing tricks. A mixin inheritance happens at compile time, when it can be type-checked statically, and it is always targeted at another class, trait, etc. Here you try to tack a trait on an existing object "on the fly" at runtime.

There are workarounds like implicit conversions, or maybe proxies. Probably the "cleanest" way would be to make Increment a wrapper class delegating to an underlying Iterator. Depending on your use case there might be other solutions.

Landei
I feel that there has got to be an implicit conversion that will solve the trick. However, the solution continues to elude me.
wheaties
+5  A: 

Figured it out. Took me a few tries to understand:

object Increment{
    implicit def convert( input:Iterator[String] ) = new Increment{
        def next() = input next
        def hasNext() = input hasNext
    }
}

and I'm done. So amazingly short.

wheaties
probably a good idea to call the method `iterator2increment`
oxbow_lakes