Scala类型推断:不能从Array [T]推断出IndexedSeq [T]

Chr*_*ris 6 arrays scala type-inference implicit-conversion scala-collections

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])    
Run Code Online (Sandbox Code Playgroud)

如果我删除类型ascription in 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)
                                                       ^
Run Code Online (Sandbox Code Playgroud)

为什么编译器不能在Array[String]这里推断?或者这个问题是否必须对从Arrays到IndexedSeqs 的隐式转换做些什么呢?

Nat*_*ate 4

问题是该.toArray方法返回某种类型的数组,该类型是inB的超类。这允许您在需要 if extends 的地方使用on 。TList[T]list.toArrayList[Bar]Array[Foo]BarFoo

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

这是我首选的解决方法:

def fromList(list: List[String]): Foo = new Foo(list.toArray[String])
Run Code Online (Sandbox Code Playgroud)