在Scala中,为什么我得到这个“多态表达式不能被实例化为期望类型
发布时间:2020-12-16 09:34:35 所属栏目:安全 来源:网络整理
导读:为什么Scala 2.9.0.1发生以下情况? scala def f(xs: Seq[Either[Int,String]]) = 0f: (xs: Seq[Either[Int,String]])Intscala val xs = List(Left(0),Right("a")).iterator.toArrayxs: Array[Product with Serializable with Either[Int,java.lang.String]]
为什么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 [任意[Int,String]]而不进行隐式转换,并且不能应用隐式转换,因为它(类型)无法确定。这就像一个鸡蛋和鸡的问题。 如果您使用<%或将其分配给val,则可以打破推理中的循环。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |