[英]scala - using asInstanceOf with Generics
我有泛型的編譯問題。 當我使用asInstanceOf
時,代碼編譯得很好。 我想擺脫asInstanceOf
。
我看到了一些與asInstanceOf
的使用有關的其他問題,但我沒有幫助我。
trait RoundRobin[R <: Resource, F[_] <: mutable.ListBuffer[_]] {
self: RoundRobin[R, F] =>
// some public functions
private def overrideMutableResourceList(original: F[R], updated: F[R]): F[R] = {
val tempPool = original.asInstanceOf[mutable.ListBuffer[R]]
original.indices.foreach(i => {
val e = updated(i).asInstanceOf[R]
tempPool.update(i, e)
})
tempPool.asInstanceOf[F[R]]
}
當我從tempPool.asInstanceOf[F[R]]
刪除asInstanceOf
,我得到以下錯誤
[error] /Users/...../RoundRobin.scala:108: type mismatch;
[error] found : tempPool.type (with underlying type scala.collection.mutable.ListBuffer[R])
[error] required: F[R]
[error] tempPool
[error] ^
[error] one error found
[error] (clustering/compile:compileIncremental) Compilation failed
[error] Total time: 3 s, completed Oct 3, 2017 2:53:34 AM
這個問題也發生在original.asInstanceOf[mutable.ListBuffer[R]]
行original.asInstanceOf[mutable.ListBuffer[R]]
asInstanceOf
? 謝謝
F[A]
和ListBuffer[A]
之間沒有關系,只有∀A∃BF[A] <: ListBuffer[B]
。 這個很重要:
type ConstLBInt[A] = ListBuffer[Int]
val x: RoundRobin[Resource, ConstLBInt] = ??? // Legal
// Tries to manipulate ListBuffer[Int]s as if they were ListBuffer[Resources]s
將類型聲明更改為
trait RoundRobin[R <: Resource, F[A] <: mutable.ListBuffer[A]]
// ! !
這迫使∀AF[A] <: ListBuffer[A]
,因此例如overrideMutableResourceList
的updated: F[R]
已知為ListBuffer[R]
。
這個類可能會被簡化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.