你可以这样做:
case class Bar()
trait Foo {
def bars : Seq[Bar]
}
case class MyFoo(bars : Seq[Bar]) extends Foo
trait Foos extends Seq[Foo] {
def bars : Seq[Bar] = this.map(_.bars).flatten
}
implicit def seqMyFooToMyFoos(myFoos:Seq[Foo]) = new Foos {
def length: Int = myFoos.length
def apply(idx: Int): Foo = myFoos(idx)
def iterator: Iterator[Foo] = myFoos.iterator
}
val foos : Foos = Seq(new MyFoo(Seq(new Bar))) // Uses implicit conversion
更新
这可能是您正在寻找的更多内容:
trait Foos {
def bars : Seq[Bar]
}
implicit def seqMyFooToMyFoos(myFoo:Seq[MyFoo]) = new Foos {
def bars : Seq[Bar] = myFoo.map(_.bars).flatten
}
val foos = Seq(new MyFoo(Seq(new Bar)))
foos.bars
更新 2
如果您使用的是 scala 2.10,则可以使用隐式类并删除 Foos 特征:
implicit class GetAllBars(myFoo:Seq[MyFoo]) {
def bars : Seq[Bar] = myFoo.map(_.bars).flatten
}
val foos = Seq(new MyFoo(Seq(new Bar)))
foos.bars