Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit conversion from array to list

How do I write an implicit conversion from Array[_] to List[_] type? I tried the following but it doesn't seem to work.

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
                                                                           ^
like image 863
Miguel Fernandez Avatar asked Feb 13 '11 04:02

Miguel Fernandez


2 Answers

implicit def arrayToList[A](a: Array[A]) = a.toList

Seems to work as expected. My guess is that there's already a genericArrayOps in Predef that has the signature for implicit conversion from Array[T] -> ArrayOps[T], ArrayOps[T] has a method .toList(): List[T]. Your method has the signature Array[T] -> List[T], which also makes the method .toList[T] available. The body is asking for an implicit conversion with that signature. The compiler doesn't know that using arrayToList will make that method go into an infinite loop, hence the ambiguity error. However, type-inferencing the return type seems to be able to work around this problem. Implicits resolution don't jive very well with type-inference it seems.

Also worth noting is that since there is already an implicit conversion that will get you what you want by default, there's no need to have an implicit conversion from Array to List.

like image 132
Y.H Wong Avatar answered Oct 25 '22 01:10

Y.H Wong


There's no need for a Manifest or ClassManifest when converting from arrays, as Array is the one "collection" type that gets special treatment on the JVM and doesn't undergo type erasure.

This means that you can go with the obvious/trivial approach, no trickery required:

implicit def arrayToList[A](arr: Array[A]) = arr.toList

One question though... Given that .toList is already such a trivial operation, what do you gain by making it implicit?

like image 42
Kevin Wright Avatar answered Oct 25 '22 01:10

Kevin Wright