Let's consider the following definition to add up all elements in a nested Iterable structure of Ints:
def add(xss : Iterable[Iterable[Int]]) : Int = xss.map(_.sum).sum
However, evaluating following expression yields a type error:
scala> add(Array(Array(1,2,3)))
<console>:9: error: type mismatch;
found : Array[Array[Int]]
required: Iterable[Iterable[Int]]
add(Array(Array(1,2,3)))
^
The function works as expected with other Iterables (like Lists). How can I avoid that error? What's the rationale for it? Guess that is something to do with Arrays being native from Java, but don't know the specifics details in this case.
Thanks
It doesn't work because Scala would need to use 2 implicit conversion in a row to go from
Array[Array[Int]]
toIterable[Iterable[Int]]
, which it (purposefully) doesn't do.You could specify the outer
Array
's type :or transform its elements to
Iterable[Int]
(thus bypassing an implicit conversion) :The problem comes from the fact that Scala's
Array[T]
is just a representation for Java'sT[]
. What makesArray[T]
behave like an usual Scala collection is an implicit conversion in Predef.From
Array
's documentation :