如何编写从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
^
命名约定`XxxOps`总是暗示你看到'Xxx`类型的延伸方法。 – 2011-02-13 11:48:00
这对我很有用。我有一个可能为null的数组(从一个JDBC调用返回,所以`Option`不是一个选项),并使用你的解释/解决方法,我可以创建一个隐式来处理它:`implicit def nullableArrayToList [T]( array:Array [T])Option(array).fold(List.empty [T]){_.toList}` – Raman 2014-05-13 17:56:55