从数组到列表的隐式转换

Mig*_*dez 7 scala implicit-conversion

如何编写隐式转换Array[_]List[_]类型?我尝试了以下但它似乎不起作用.

scala> implicit def arrayToList[A : ClassManifest](a: Array[A]): List[A] = a.toList
<console>:5: error: type mismatch;
 found   : Array[A]
 required: ?{val toList: ?}
Note that implicit conversions are not applicable because they are ambiguous:
 both method arrayToList in object $iw of type [A](a: Array[A])(implicit evidence$1: ClassManifest[A])List[A]
 and method genericArrayOps in object Predef of type [T](xs: Array[T])scala.collection.mutable.ArrayOps[T]
 are possible conversion functions from Array[A] to ?{val toList: ?}
       implicit def arrayToList[A : ClassManifest](a: Array[A]): List[A] = a.toList
                                                                           ^
Run Code Online (Sandbox Code Playgroud)

Y.H*_*ong 10

implicit def arrayToList[A](a: Array[A]) = a.toList
Run Code Online (Sandbox Code Playgroud)

似乎按预期工作.我的猜测是,已经有一个genericArrayOpsPredef具有用于从隐式转换签名Array[T] -> ArrayOps[T],ArrayOps[T]有一个方法.toList(): List[T].您的方法具有签名Array[T] -> List[T],这也使该方法.toList[T]可用.正文要求使用该签名进行隐式转换.编译器不知道使用arrayToList会使该方法进入无限循环,因此模糊错误.但是,类型推断返回类型似乎能够解决此问题.看起来,类型推断暗示解决方案并不是很好.

另外值得一提的是,既然已经有你想用默认什么的隐式转换,将让你,有没有必要有从隐式转换ArrayList.


Kev*_*ght 7

不需要a ManifestClassManifest何时数组转换,就像Array在JVM上获得特殊处理并且不进行类型擦除的一种"集合"类型一样.

这意味着你可以采用明显/琐碎的方法,不需要任何技巧:

implicit def arrayToList[A](arr: Array[A]) = arr.toList
Run Code Online (Sandbox Code Playgroud)

但是有一个问题......鉴于这.toList已经是一个微不足道的操作,你通过暗示它获得了什么?