我的代码很简单:为什么Scala编译器认为存在多态类型错误?
class MyClass {
var foo: IndexedSeq[MyClass] = IndexedSeq()
def bar(newValues: MyClass*) = foo = newValues.toArray
}
类包含一个变量和方法。变量foo
是MyClass
对象的IndexSeq
。它还包含一个方法bar
,它将MyClass
对象的参数设置为Seq
。由于Seq[T]
不能被分配到IndexSeq[T]
,因为后者是前者的一个子类,我不得不打电话给toArray
。
有了这个代码,编译器会抱怨如下
polymorphic expression cannot be instantiated to expected type;
found : [B >: MyClass]Array[B]
required: IndexedSeq[MyClass]
def bar(newValues: MyClass*) = foo = newValues.toArray
^
于是我找到了一个解决方案,这是调用toIndexSeq
而不是toArray
,而编译器不会再抱怨了。
即使问题没有解决,我仍然想知道为什么会出现这样的错误。
[Scala隐式转换从Array \ [T \]到IndexedSeq \ [T \]]的可能重复(http://stackoverflow.com/questions/26704028/scala-implicit-conversion-from-arrayt-to-indexedseqt) – 2015-03-19 03:28:51