簡體   English   中英

scala - 在泛型中使用asInstanceOf

[英]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] ,因此例如overrideMutableResourceListupdated: F[R]已知為ListBuffer[R]

這個類可能會被簡化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM