简体   繁体   中英

Why does Scala compiler think there is a polymorphic type error?

My code is simple:

class MyClass {
  var foo: IndexedSeq[MyClass] = IndexedSeq()
  def bar(newValues: MyClass*) = foo = newValues.toArray
}

The class contains a variable and a method. The variable foo is an IndexSeq of MyClass objects. It also contains a method bar which takes as parameters a Seq of MyClass objects. Because a Seq[T] cannot be assigned to a IndexSeq[T] , since the latter is a subclass of the former, I had to call toArray .

With this code, the compiler complains as follows

polymorphic expression cannot be instantiated to expected type;
 found   : [B >: MyClass]Array[B]
 required: IndexedSeq[MyClass]
  def bar(newValues: MyClass*) = foo = newValues.toArray
                                                 ^

So I found a solution, which is to call toIndexSeq instead of toArray , and the compiler does not complain anymore.

Even though the problem is gone for me, I still wonder why there was such an error.

If you look at the spec for Array , you'll notice that it does not extend Seq or IndexedSeq . In fact, Array is pretty a bare-bones class that extends only Serializable and Cloneable , because it is based on the Java Array implementation. You're probably used to treating it like a Seq because of the implicit conversions available on Array , in ArrayOps .

The problem is that there is no implicit conversion from Array[B >: MyClass] (which is what is returned by toArray ) to IndexedSeq[MyClass] . If you explicitly provide the generic parameter of toArray or use type ascription, this problem is solved, because there is an implicit conversion from Array[MyClass] to Seq[MyClass] :

def bar(newValues: MyClass*) = foo = newValues.toArray[MyClass]
def bar(newValues: MyClass*) = foo = (newValues.toArray : Array[MyClass])

This even simpler example might help elucidate:

class Foo
Seq(new Foo).toArray : Seq[Foo] //fails
Seq(new Foo).toArray[Foo] : Seq[Foo] //works!
(Seq(new Foo).toList.toArray : Array[Foo]) : Seq[Foo] //also works!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM