3
votes

I have Seq[Seq[Byte]] type defined in function parameter in Scala.

def checkAllZeroElementsInTable(table: Seq[Seq[Byte]]) : Boolean = {
...

When I give an argument of type Array[Array[Byte]], I got Type mismatch error.

val table = Array(Array[Byte](0,0,0),Array[Byte](0,0,0),Array[Byte](0,0,0),Array[Byte](0,0,1))

This is the error message:

enter image description here

The simplest solution is to redefine the function, but I think this is not the best solution.

def checkAllZeroElementsInTable(table: Array[Array[Byte]]) : Boolean = {
...

Why this error, and how to solve this issue?

2
I'd recommend using view bounds, as shown in this answer to a similar problem.ggovan

2 Answers

4
votes

Surprisingly, Array is not a Sequence, at least through the usual means of inheritance as @Brian noted. But in addition -- the problem arises because you use nested arrays and because of the way implicit conversions works in scala.

First, compiler goes through all your code and happily moves bits and bolts. Now, if there is typecheck error it looks into a list of implicit conversions it allowed to perform in order to fix otherwise non-compilable code (one for them is Array => Seq). So compiler sees Seq[Seq[Byte]] on the left hand side and tries to apply that conversion. What it gots on the right hand side after such application? Right, it gots Seq[Array[Byte]] which is not Seq[Seq[Byte]].

enter image description here

So this fix attempt has failed and eventially compiler bails out with that error: Type mismatch, blah blah blah. As you already may guess, implicit conversions do not go into depth (which is sane rule, actually). But, in this example, scalac will happily typecheck and compile such code:

def foo(seq: Seq[Array[Int]]) = println(seq)
foo(Array(Array(1)))
// WrappedArray([I@afb9176)

The solution is, sadly, to use Seqs initially, because I don't think that manual conversion of enclosed array is a viable option for you.

EDIT: in fact, it also fails because there is no implicit conversion, which is aimed on converting collection's element, but if you will introduce one, you will be stopped by the mechanisms explained above (however, it can be solved with additional hassle)

1
votes

The error is because Array is not of type Seq. Array is Scala's representation of a Java array.

The type hierarchy for Array shows that it is does not inherit from Seq as your error message says. Array type hierarchy

You can change your function to take an Array as you note. If you need a mutable collection, take a look at scala.collection.mutable.ArrayBuffer. For immutable collections there are other options and the best choice depends on how your algorithm accesses the collection. This has good info on collection characteristics: http://www.scala-lang.org/docu/files/collections-api/collections_40.html