gpt4 book ai didi

scala - 创建一个自定义 Scala 集合,其中 map 默认返回自定义集合?

转载 作者:行者123 更新时间:2023-12-04 15:24:30 25 4
gpt4 key购买 nike

性状 TraversableLike[+A, +Repr]允许创建一个集合,其中某些函数将返回 Repr ,而其他人则继续返回类型参数 That在功能上。有没有办法定义 CustomCollection[A]其中函数类似于 map , ++ , 其他人将默认 ThatRepr如果不是以其他方式推断?

这是一个代码片段,希望能描述我想要的:

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) .

最佳答案

您需要设置一个配套对象,提供精炼的 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]

关于scala - 创建一个自定义 Scala 集合,其中 map 默认返回自定义集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14299454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com