【发布时间】:2013-01-13 00:32:59
【问题描述】:
特征TraversableLike[+A, +Repr] 允许创建一个集合,其中一些 函数将返回Repr,而其他函数继续返回函数的类型参数That。有没有办法定义CustomCollection[A],其中map、++ 和其他函数将默认That 为Repr,如果不是以其他方式推断?
这是一个代码 sn-p,希望能描述我想要的:
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)。
【问题讨论】:
-
我只为 +1 om-nom-nom 登录,因为仅落后帖子三分钟。似乎没有“及时编辑!”带有竖起大拇指标志的按钮。
标签: scala collections type-inference scala-collections scala-2.10