agr*_*inh 2 arrays scala implicit scala-2.10 scala-2.11
我遇到了一个问题,试图创建一个适用于所有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的子类.
就像@goral所说:一次只能进行一次隐式转换.
因此,您可以传递一个预期Traversable的数组,因为Array将成为WrappedArray:
def printme[T](a: Traversable[T]) { for (b <- a) print(b) }
printme(Vector(1,2,3))
printme(Array(1,2,3))
Run Code Online (Sandbox Code Playgroud)
或者您可以在手动包装的数组上使用隐式:
val wa = scala.collection.mutable.WrappedArray.make(Array(1, 2, 3))
wa.printme
Run Code Online (Sandbox Code Playgroud)
但你不能同时拥有两者.