gpt4 book ai didi

scala - Predef.StringCanBuildFrom 的行为

转载 作者:行者123 更新时间:2023-12-04 20:32:48 24 4
gpt4 key购买 nike

我偶然发现Predef.StringCanBuildFrom令人惊讶的实现打破了我在 CanBuildFrom 上所做的假设在我的代码中。这是实现:

implicit def stringCanBuildFrom: CanBuildFrom[String, Char, String] = 
new CanBuildFrom[String, Char, String] {
def apply(from: String) = apply()
def apply() = mutable.StringBuilder.newBuilder
}
apply(String)似乎完全不自然简单地忽略参数。对我来说,正确的实现应该是
implicit def stringCanBuildFrom: CanBuildFrom[String, Char, String] = 
new CanBuildFrom[String, Char, String] {
def apply(from: String) = apply() ++= from
def apply() = mutable.StringBuilder.newBuilder
}

但这似乎微不足道,以至于我无法相信我是唯一一个发现这种语言的人,因为该语言存在。我很想为此打开一个问题,但是如果我缺少任何不执行我建议的好理由,请告诉我!

最佳答案

我想你误解了apply(from)的目的.

它的文档说:

Creates a new builder on request of a collection.
@param from the collection requesting the builder to be created.
@return a builder for collections of type To with element type Elem. The collections framework usually arranges things so that the created builder will build the same kind of collection as from.



所以它用于使用集合的运行时类型来解析构建器,并且可能从原始集合中复制一些辅助数据。例如 scala.collection.generic.GenTraversableFactory#GenericCanBuildFrom中的实现就是 def apply(from: Coll) = from.genericBuilder[A] .如您所见,没有从参数集合中复制实际数据。

实际上,您对 CanBuildFrom 的实现会为 map 的标准实现产生错误的结果, flatMap和其他通用功能:
import scala.collection.generic.CanBuildFrom
import scala.collection.mutable

implicit def stringCanBuildFrom: CanBuildFrom[String, Char, String] =
new CanBuildFrom[String, Char, String] {
def apply(from: String) = apply() ++= from
def apply() = mutable.StringBuilder.newBuilder
}

scala> "foo".map(identity)(stringCanBuildFrom)
res1: String = foofoo

关于scala - Predef.StringCanBuildFrom 的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41786084/

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