【发布时间】:2014-12-27 23:01:40
【问题描述】:
在 Scala 2.11.2 中,以下最小示例仅在 Array[String] 上使用 type 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's 到IndexedSeq's 的隐式转换有关?
【问题讨论】:
-
注意我认为你可以这样做:
object Foo { def fromList(list: List[String]): Foo = new Foo(list.toArray[String])}。 -
当然也可以是
list.toIndexedSeq。不过,这个问题仍然很好。 -
感谢您指出这一点。我选择
Arrays 而不是IndexedSeqs 的原因纯粹是出于性能原因。我不得不对函数进行分析,发现Vectors 在创建大量小实例时会占用更多开销。
标签: arrays scala implicit-conversion type-inference scala-collections