Dependency in traits inheritance
In Scala, how can i add a container trait (like Traversable[Content]) to another one that extends the container (and thus has limited visibility of its content ?
For example, the code below tries to define a trait WithIter for a container requiring Traversable (of course, i have in fact other things in Container).
import scala.collection._
trait Container {
type Value
}
trait WithIter exte开发者_开发技巧nds Container with immutable.Traversable[Container#Value]
class Instance extends WithIter {
type Value = Int
def foreach[U](f : (Value) => (U)) : Unit = {}
}
Compiler (scalac 2.8.0.Beta1-RC8) finds an error:
error: class Instance needs to be abstract, since method foreach in trait GenericTraversableTemplate of type [U](f: (Container#Value) => U)Unit is not defined
Is there any simple way?
class Instance extends WithIter {
type Value = Int
def foreach[U](f : (Container#Value) => (U)) : Unit = {}
}
If you do not specify OuterClass#
when speaking of an inner class, then this.
(ie, instance-specific) will be assumed.
Why do you use an abstract type? Generics are straightforward:
import scala.collection._
trait Container[T] {}
trait WithIter[T] extends Container[T] with immutable.Traversable[T]
class Instance extends WithIter[Int] {
def foreach[U](f : (Int) => (U)) : Unit = {println(f(1))}
}
new Instance().foreach( (x : Int) => x + 1)
精彩评论