6

この特性TraversableLike[+A, +Repr]により、一部の関数がを返すコレクションを作成し、Repr他の関数は関数の型パラメーターを返し続けることができますThatCustomCollection[A]、、などの関数が、他の方法で推測されないかのようにデフォルトになる場所mapを定義++するThat方法はありますか?Repr

これが私が欲しいものをうまく説明するコードスニペットです:

case class CustomCollection[A](list: List[A]) extends TraversableLike[A, CustomCollection[A]] {
  protected[this] def newBuilder = new CustomCollectionBuilder[A]
  def foreach[U](f: (A) => U) {list foreach f}
  def seq = list
}

class CustomCollectionBuilder[A] extends mutable.Builder[A, CustomCollection[A]] {
  private val list = new mutable.ListBuffer[A]()
  def += (elem: A): this.type = {
    list += elem
    this
  }
  def clear() {list.clear()}
  def result(): CustomCollection[A] = CustomCollection(list.result())
}

object CustomCollection extends App {
  val customCollection = CustomCollection(List(1, 2, 3))
  println(customCollection filter {x => x == 1}) // CustomCollection(1)
  println(customCollection map {x => x + 1}) // non-empty iterator
}

最後の行を。にしたいのですがCustomCollection(2, 3, 4)

4

1 に答える 1

4

CanBuildFrom洗練されたインスタンスを提供するコンパニオンオブジェクトを設定する必要があります。

import collection.TraversableLike
import collection.generic.{CanBuildFrom, GenericCompanion, GenericTraversableTemplate,
  TraversableFactory}
import collection.mutable.{Builder, ListBuffer}

object CustomCollection extends TraversableFactory[CustomCollection] {
  def newBuilder[A] = new CustomCollectionBuilder[A]
  implicit def canBuildFrom[A]: CanBuildFrom[Coll, A, CustomCollection[A]] = 
    new CanBuildFrom[Coll, A, CustomCollection[A]] {
       def apply(): Builder[A, CustomCollection[A]] = new CustomCollectionBuilder()
       def apply(from: Coll): Builder[A, CustomCollection[A]] = apply()
    }
}
case class CustomCollection[A](list: List[A]) extends Traversable[A]
with TraversableLike[A, CustomCollection[A]]
with GenericTraversableTemplate[A, CustomCollection] {
  override def companion: GenericCompanion[CustomCollection] = CustomCollection
  def foreach[U](f: A => U) { list foreach f }
  override def seq = list
}

class CustomCollectionBuilder[A] extends Builder[A, CustomCollection[A]] {
  private val list = new ListBuffer[A]()
  def += (elem: A): this.type = {
    list += elem
    this
  }
  def clear() {list.clear()}
  def result(): CustomCollection[A] = CustomCollection(list.result())
}

val customCollection = CustomCollection(List(1, 2, 3))
val f = customCollection filter {x => x == 1} // CustomCollection[Int]
val m = customCollection map {x => x + 1}     // CustomCollection[Int]
于 2013-01-13T01:14:45.190 に答える