加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – Predef.StringCanBuildFrom的行为

发布时间:2020-12-16 18:36:55 所属栏目:安全 来源:网络整理
导读:我偶然发现Predef.StringCanBuildFrom令人惊讶的实现,打破了我在我的代码中对CanBuildFrom所做的假设.这是实施: implicit def stringCanBuildFrom: CanBuildFrom[String,Char,String] = new CanBuildFrom[String,String] { def apply(from: String) = apply
我偶然发现Predef.StringCanBuildFrom令人惊讶的实现,打破了我在我的代码中对CanBuildFrom所做的假设.这是实施:

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

apply(String)简单地忽略参数似乎完全不自然.对我来说,正确的实施应该是

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

但这似乎是微不足道的,以至于我无法相信我是那个因为语言存在而发现它的人.我很想为此开一个问题,但是如果我错过任何没有理由不做我的建议,请告诉我!

解决方法

我认为你误解了申请的目的(来自).

它的文件说:

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,String] =
  new CanBuildFrom[String,String] {
    def apply(from: String) = apply() ++= from
    def apply() = mutable.StringBuilder.newBuilder
  }

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读