首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Scala中,为什么我会得到这样的“多态表达式不能实例化为预期的类型”?

在Scala中,为什么我会得到这样的“多态表达式不能实例化为预期的类型”?
EN

Stack Overflow用户
提问于 2011-07-13 15:20:48
回答 3查看 14K关注 0票数 25

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

代码语言:javascript
复制
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%确定这是在演示相同的潜在现象):

代码语言:javascript
复制
Seq(0).toArray : Seq[Int] // compiles
Seq(Some(0)).toArray : Seq[Option[Int]] // doesn't
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6675419

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档