Scala: convert return type to custom attribute

I wrote a custom tag that extends Iterator [A], and I would like to be able to use the methods that I wrote on Iterator [A], which is returned from another method. Is it 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 figure out all this stuff and don't really like writing a method in the definition of a Bar object. How can I wrap such an element to work the way I would like above?

+4
source share
2 answers

Figured it out. It took several attempts to understand:

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

and i finished. So amazingly short.

+6
source

I do not think this is possible without tricks. The mixin inherits at compile time, when it can be type checked statically, and it always targets a different class, trait, etc. Here you are trying to identify a feature of an existing object on the fly at runtime.

There are workarounds, such as implicit conversions or possibly proxies. Probably the cleanest way would be to make Increment a wrapper class delegating the underlying Iterator. There may be other solutions, depending on your use case.

+2
source

All Articles