【问题标题】:scala - using asInstanceOf with Genericsscala - 将 asInstanceOf 与泛型一起使用
【发布时间】:2017-10-03 03:00:41
【问题描述】:

我遇到了泛型编译问题。当我使用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]] 行也会出现此问题

  • 出现此问题的原因是什么?
  • 如何避免使用asInstanceOf

谢谢

【问题讨论】:

    标签: scala generics casting type-inference


    【解决方案1】:

    F[A]ListBuffer[A] 之间没有关系,只有 ∀A∃B F[A] &lt;: 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]]
    //                                !                        !
    

    这会强制∀A F[A] &lt;: ListBuffer[A],例如overrideMutableResourceList 中的 updated: F[R] 被称为 ListBuffer[R]

    这个类的其他部分可能会被简化。

    【讨论】:

      猜你喜欢
      • 2017-10-14
      • 1970-01-01
      • 2011-02-09
      • 2019-03-21
      • 2015-09-12
      • 2010-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多