Scala中2.11.2,下面的最小例如使用当仅编译类型归属于Array[String]
:
object Foo {
def fromList(list: List[String]): Foo = new Foo(list.toArray : Array[String])
}
class Foo(source: IndexedSeq[String])
如果我删除中的类型说明fromList
,它将无法编译并出现以下错误:
Error:(48, 56) polymorphic expression cannot be instantiated to expected type;
found : [B >: String]Array[B]
required: IndexedSeq[String]
def fromList(list: List[String]): Foo = new Foo(list.toArray)
^
为什么编译器不能在Array[String]
这里推断?还是这个问题与从Array
到的隐式转换有关IndexedSeq
?
问题在于该.toArray
方法返回某种类型的Array,B
它是T
in的超类List[T]
。这使您可以使用list.toArray
上List[Bar]
,其中一个Array[Foo]
是否需要Bar
延长Foo
。
是的,这个开箱即用的真正原因是编译器试图弄清楚B
使用哪个以及如何获取IndexedSeq
。似乎正在尝试解决IndexedSeq[String]
要求,但B
只能保证它是的一个String
或超类String
;因此错误。
这是我首选的解决方法:
def fromList(list: List[String]): Foo = new Foo(list.toArray[String])
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句