Implicit conversion from array to list

30,968

Solution 1

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.

Solution 2

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?

Share:
30,968
Miguel Fernandez
Author by

Miguel Fernandez

Updated on February 14, 2020

Comments

  • Miguel Fernandez
    Miguel Fernandez about 4 years

    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
                                                                               ^
    
  • Kevin Wright
    Kevin Wright about 13 years
    The naming convention XxxOps always suggests that you're seeing pimped extension methods for the type Xxx
  • Raman
    Raman almost 10 years
    This was useful to me. I have an array that might be null (returned from a JDBC call, so Option is not an option), and using your explanation/workaround I was able to create an implicit to handle it: implicit def nullableArrayToList[T](array: Array[T]) Option(array).fold(List.empty[T]) { _.toList }