次の 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 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 cannot be cast to 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 -- Copyright 2002-2012、LAMP/EPFL