Scala 集合代码涉及mutable.IndexedSeq、view、take和grouped抛出ClassCastException
下面的scala代码编译得很好Scala 集合代码涉及mutable.IndexedSeq、view、take和grouped抛出ClassCastException,scala,casting,scala-collections,Scala,Casting,Scala Collections,下面的scala代码编译得很好 object Main extends App { import scala.collection.mutable.IndexedSeq def doIt() { val nums: IndexedSeq[Int] = Array(3,5,9,11) val view: IndexedSeq[Int] = nums.view val half: IndexedSeq[Int] = view.take(2) val grou
object Main extends App {
import scala.collection.mutable.IndexedSeq
def doIt() {
val nums: IndexedSeq[Int] = Array(3,5,9,11)
val view: IndexedSeq[Int] = nums.view
val half: IndexedSeq[Int] = view.take(2)
val grouped: Iterator[IndexedSeq[Int]] = half.grouped(2)
val firstPair: IndexedSeq[Int] = grouped.next() //throws exception here
}
doIt()
}
但是,在运行时,它认为不能将java.lang.ClassCastException:scala.collection.SeqViewLike$$anon$1转换为scala.collection.mutable.IndexedSeq
在调用时grouped.next()
我希望对grouped.next()
的调用返回的值等于IndexedSeq[Int](3,5)
我想知道为什么这个代码失败了,如果有一个正确的方法来修复它
如果我在REPL中重复相同的步骤,类型信息会确认代码编译的原因,但不会让我了解引发异常的原因:
scala> val nums = Array(3,5,9,11)
nums: Array[Int] = Array(3, 5, 9, 11)
scala> val view = nums.view
view: scala.collection.mutable.IndexedSeqView[Int,Array[Int]] = SeqView(...)
scala> val half = view.take(2)
half: scala.collection.mutable.IndexedSeqView[Int,Array[Int]] = SeqViewS(...)
scala> val grouped = half.grouped(2)
grouped: Iterator[scala.collection.mutable.IndexedSeqView[Int,Array[Int]]] = non-empty iterator
scala> val firstPair = grouped.next()
java.lang.ClassCastException: scala.collection.SeqViewLike$$anon$1 cannot be cast to scala.collection.mutable.IndexedSeqView
Scala版本2.10.0-20121205-235900-18481cef9b——版权所有2002-2012,LAMP/EPFL看起来您遇到了可复制的Scala 2.10.0 FinalTanks,用于查找错误报告并将我的情况中的相关信息添加到其中。