爲了獲得更多有關Scala的經驗,作爲一個實驗,我實現了一個具有類似List
的API的類,但實現爲包含第一個元素的索引的IndexedSeq
列表; tail
僅返回與遞增索引的副本,並在前面加上Array
s是O(1),而追加Array
s是O(M)中,m =列表< =元素的數目的長度。Scala:類型不匹配,返回BlockList [Any]而不是BlockList [R]
我正在與我的函數返回類型的問題。幾乎每種方法都有類型參數[R >: T : ClassManifest, A <: R : ClassManifest]
,T
是BlockList
的類型參數。有時這些方法只會返回其他方法,但在這些情況下,我從Eclipse中得到一個錯誤,說它正在尋找類型BlockList[R]
,但發現類型爲BlockList[Any]
。不應該R
是T
和A
的最低通用超級類型?在這種情況下,第二個方法調用也應該返回BlockList[R]
,對吧?我沒有得到什麼?我反映ClassManifest
很多以克服類型擦除的問題,但我不知道它是否仍然是一個問題。
的錯誤是從|:
和:|
的定義。
import collection.immutable.List
import reflect.ClassManifest
import annotation.tailrec
sealed abstract
class BlockList [+T] extends Seq[T] with Product {
...
}
object EmptyBlock extends BlockList[Nothing] {
...
}
class Build [T: ClassManifest](
private val block: IndexedSeq[T],
private val next: BlockList[T] = EmptyBlock,
private val index: Int = 0
) extends BlockList[T] {
require(!block.isEmpty && index >= 0 && index < block.length)
override def |: [R >: T : ClassManifest, A <: R] (x: A): BlockList[R] =
Array[R](x) |: this //Return type error here
override def |: [R >: T : ClassManifest, A <: R : ClassManifest]
(blk: IndexedSeq[A]): BlockList[R] =
if (blk isEmpty) this
else new Build[R](blk, this)
override def :| [R >: T : ClassManifest, A <: R] (x: A): BlockList[R] =
this :| Array[R](x) //Return type error here
override def :| [R >: T : ClassManifest, A <: R : ClassManifest]
(blk: IndexedSeq[A]): BlockList[R] =
if (blk isEmpty) this
else new Build[R](block, next :| blk, index) //Type error here
}
我建議簡化到產生錯誤的最小可能的例子。 – Brian
謝謝Brian。我接受了你的建議。 – Eric