在 Scala 中,为什么我会得到这个“无法将多态表达式实例化为预期类型"? [英] In Scala, why do I get this "polymorphic expression cannot be instantiated to expected type"?

查看:41
本文介绍了在 Scala 中,为什么我会得到这个“无法将多态表达式实例化为预期类型"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在 Scala 2.9.0.1 中会出现以下情况?

Why does the following occur in 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% 确定这证明了相同的潜在现象):

Update: Debilski suggests a better example (not 100% sure this is demonstrating the same underlying phenomenon):

Seq(0).toArray : Seq[Int] // compiles
Seq(Some(0)).toArray : Seq[Option[Int]] // doesn't

推荐答案

解释这个问题的最佳人选是 Adriaan Moors,他已经在 Stack Overflow 上做了这件事——从他那里查找答案,你就会找到答案.

The best person to explain this is Adriaan Moors, and he already did that here on Stack Overflow -- lookup answers from him and you'll find it.

不管怎样,问题是List(Left(0), Right("a")).iterator.toArray的类型不能在f<期望的边界内推断出来/代码>.它不符合 Seq[Either[Int, String]] 没有隐式转换,并且不能应用隐式转换,因为它(类型)无法确定.这就像鸡蛋和鸡肉的问题.

Anyway, the problem is that the type of List(Left(0), Right("a")).iterator.toArray cannot be inferred within the boundaries expected by f. It does not conform to Seq[Either[Int, String]] without an implicit conversion, and no implicit conversion can be applied because it (the type) cannot be determined. It's like an egg&chicken problem.

如果您使用 <% 或将其分配给一个 val,则会打破推理中的循环.

If you use <% or assign it to a val, you break the cycle in the inference.

这篇关于在 Scala 中,为什么我会得到这个“无法将多态表达式实例化为预期类型"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆