4

我有以下内容:

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
}

我想转换 to 的对象Seq[MyFoo]MyFoos最好是隐式的。一个人怎么能做到这一点?

例如。

val foos : Foos = Seq(new MyFoo(Seq(new Bar)))
4

1 回答 1

5

你可以这样做:

  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
于 2013-03-30T03:00:20.137 回答