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

scala – 编写通用的“填充”方法

发布时间:2020-12-16 18:57:58 所属栏目:安全 来源:网络整理
导读:我正在尝试编写一个通用的填充方法,以下是我到目前为止所提出的方法: scala import collection.generic.{GenericTraversableTemplate = GTT}import collection.generic.{GenericTraversableTemplate=GTT}scala import collection.generic.{TraversableFacto
我正在尝试编写一个通用的填充方法,以下是我到目前为止所提出的方法:

scala> import collection.generic.{GenericTraversableTemplate => GTT}
import collection.generic.{GenericTraversableTemplate=>GTT}

scala> import collection.generic.{TraversableFactory => TF}
import collection.generic.{TraversableFactory=>TF}

scala> def fill[A,CC[X] <: Traversable[X] with GTT[X,CC]]
     |   (n: Int)(elem: => A)(tf: TF[CC]) = tf.fill(n)(elem)
fill: [A,CC[X] <: Traversable[X] with scala.collection.generic.GenericTraversab
leTemplate[X,CC]](n: Int)(elem: => A)(tf: scala.collection.generic.TraversableFa
ctory[CC])CC[A]

scala> fill(3)('d')(List)
res42: List[Char] = List(d,d,d)

这适用于除数组之外的所有可遍历集合.如何使此代码与数组一起使用?

解决方法

如果你不介意创建一个额外的对象,那就是

def fill[CC[_]](n: Int) = new {
  def apply[A](elem: => A)(implicit cbf: CanBuildFrom[Nothing,A,CC[A]]) = {
    val b = cbf()
    1 to n foreach { _ => b += elem }
    b.result
  }
}

它没有绕过异议(2),但用法很好:

scala> fill[List](3)("wish")
res0: List[java.lang.String] = List(wish,wish,wish)

scala> fill[Array](3)("wish")
res1: Array[java.lang.String] = Array(wish,wish)

(编辑:李大同)

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

    推荐文章
      热点阅读