作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我偶然发现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 typeTo
with element typeElem
. The collections framework usually arranges things so that the created builder will build the same kind of collection asfrom
.
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/
我偶然发现Predef.StringCanBuildFrom令人惊讶的实现打破了我在 CanBuildFrom 上所做的假设在我的代码中。这是实现: implicit def stringCanBui
我是一名优秀的程序员,十分优秀!