scala - 在 Scala 中,为什么我会得到这个 "polymorphic expression cannot be instantiated to expected type"?

标签 scala

为什么在 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/

相关文章:

scala - 隐式添加对象方法

scala - 如何使用 Mockito 在 Scala 对象中模拟函数?

scala 类使用泛型扩展特征,泛型是字段的一种类型

scala - 解密最困难的Scala方法原型(prototype)之一(平滑)

scala - 使用框架 REST 进行基本身份验证和 SSL

scala - 如何让ensime在windows下运行?

java - 如何在 Scala 中使用 Java 包 com.example...object

scala - Spark 上的动态集合代数

java - 有没有办法在 Scala 中的方法参数中声明一组指定的值?

scala - Spark mllib f1score 阈值