小编agr*_*inh的帖子

适用于所有Traversable子类(包括Array)的隐式类

我遇到了一个问题,试图创建一个适用于所有Traversable子类(包括Array)的隐式类.我在Scala 2.11.1和2.10.4中尝试了以下简单示例:

implicit class PrintMe[T](a: Traversable[T]) {
  def printme = for (b <- a) print(b)
}
Run Code Online (Sandbox Code Playgroud)

据我所知,这应该允许隐式转换为PrintMe,以便可以在任何Traversable上调用printme,包括List和Array.例如:

scala> List(1,2,3).printme
123
// Great, works as I expected!

scala> Array(1,2,3).printme
<console>:23: error: value printme is not a member of Array[Int]
              Array(1,2,3).printme
// Seems like for an Array it doesn't!

scala> new PrintMe(Array(1,2,3)).printme
123
// Yet explicitly building a PrintMe from an Array works 
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?为什么隐式转换适用于List而不是数组?

我知道有一些技巧适应java Arrays但是从http://docs.scala-lang.org/overviews/collections/overview.html查看下面的图片看起来似乎Array的行为就像Traversable的子类.

scala.collection.immutable

arrays scala implicit scala-2.10 scala-2.11

2
推荐指数
1
解决办法
354
查看次数

标签 统计

arrays ×1

implicit ×1

scala ×1

scala-2.10 ×1

scala-2.11 ×1