Search code examples
scalaimplicitimplicit-conversionimplicit-typing

Scala: convert a return type into a custom trait


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?


Solution

  • 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.