Alex Rivera | Logout

In Scala, why do I get this "polymorphic expression cannot be instantiated to expected type"?

Asked 2011-07-13T07:20:47.690
26

Why does the following occur in Scala 2.9.0.1?

scala> def f(xs: Seq[Either[Int,String]]) = 0
f: (xs: Seq[Either[Int,String]])Int

scala> val xs = List(Left(0), Right("a")).iterator.toArray
xs: Array[Product with Serializable with Either[Int,java.lang.String]] = Array(Left(0), Right(a))

scala> f(xs)
res39: Int = 0

scala> f(List(Left(0), Right("a")).iterator.toArray)
<console>:9: error: polymorphic expression cannot be instantiated to expected type;
 found   : [B >: Product with Serializable with Either[Int,java.lang.String]]Array[B]
 required: Seq[Either[Int,String]]
       f(List(Left(0), Right("a")).iterator.toArray)
                                            ^

Update: Debilski suggests a better example (not 100% sure this is demonstrating the same underlying phenomenon):

Seq(0).toArray : Seq[Int] // compiles
Seq(Some(0)).toArray : Seq[Option[Int]] // doesn't
Edit
Report

1 Answer

2

I believe this is because you cannot turn an Array into an Array, but you can convert a Sequence into an Array. The method wants a Sequence that it can use to make an Array.

Bottom line is to check the method signatures and not guess what they are based on the method name.

The important part is this:

found   : [B >: Product with Serializable with Either[Int,java.lang.String]]Array[B]
 required: Seq[Either[Int,String]]
       f(List(Left(0), Right("a")).iterator.toArray)

The toArray method wants a Seq (so a List would be fine) and it returns an Array. You have passed it an Array and it does not know what to do. Either make the Array into a Seq first, or just skip the toArray method entirely.

If you go back one step it is clear that the iterator method takes your List and returns an Array. Each method invocation is a function call.

answered 2011-07-13T08:34:34.533

Your Answer