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 开发者_如何学JAVAI'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?
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.
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.
精彩评论