在
Scala 2.11.2中,以下最小示例仅在Array [String]上使用类型ascription时进行编译:
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方法返回某个类型B的数组,它是List [T]中T的超类.这允许您在List [Bar]上使用list.toArray,如果Bar扩展Foo,则需要Array [Foo].
是的,这个开箱即用的真正原因是编译器试图找出使用哪个B以及如何到达IndexedSeq.它似乎正在尝试解决IndexedSeq [String]要求,但B只能保证是String或String的超类;因此错误.
这是我的首选工作:
def fromList(list: List[String]): Foo = new Foo(list.toArray[String])