为什么在 Scala 2.9.0.1 中会出现以下情况?
scala> def f(xs: Seq[Either[Int,String]]) = 0
f: (xs: Seq[Either[Int,String]])Int
scala> val xs = List(Left(0), Right("a")).iterator.toArray
xs: Array[Product with Serializable with Either[Int,java.lang.String]] = Array(Left(0), Right(a))
scala> f(xs)
res39: Int = 0
scala> f(List(Left(0), Right("a")).iterator.toArray)
<console>:9: error: polymorphic expression cannot be instantiated to expected type;
found : [B >: Product with Serializable with Either[Int,java.lang.String]]Array[B]
required: Seq[Either[Int,String]]
f(List(Left(0), Right("a")).iterator.toArray)
^
更新 :Debilski 提出了一个更好的例子(不是 100% 确定这证明了相同的潜在现象):
Seq(0).toArray : Seq[Int] // compiles
Seq(Some(0)).toArray : Seq[Option[Int]] // doesn't
最佳答案
解释这一点的最佳人选是 Adriaan Moors,他已经在 Stack Overflow 上这样做了——从他那里查找答案,你就会找到答案。
反正问题是List(Left(0), Right("a")).iterator.toArray
的类型无法在 f
预期的边界内推断出来.不符合Seq[Either[Int, String]]
没有隐式转换,也不能应用隐式转换,因为它(类型)无法确定。这就像一个鸡蛋和鸡肉的问题。
如果您使用 <%
或者将它分配给一个 val,你就打破了推理中的循环。
关于scala - 在 Scala 中,为什么我会得到这个 "polymorphic expression cannot be instantiated to expected type"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6675419/