【问题标题】:Scala type inference: can't infer IndexedSeq[T] from Array[T]Scala 类型推断:无法从 Array[T] 推断 IndexedSeq[T]
【发布时间】: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


【解决方案1】:

问题是.toArray 方法返回某种类型的数组B,它是List[T]T 的超类。这允许您在List[Bar] 上使用list.toArray,如果Bar 扩展Foo,则需要Array[Foo]

是的,这不能开箱即用的真正原因是编译器试图找出使用哪个B 以及如何获得IndexedSeq。似乎它正在尝试解决IndexedSeq[String] 的要求,但B 只能保证是StringString 的超类;因此错误。

这是我首选的解决方法:

def fromList(list: List[String]): Foo = new Foo(list.toArray[String])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-01
    • 2020-07-05
    相关资源
    最近更新 更多