首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >scala -使用Generics的asInstanceOf

scala -使用Generics的asInstanceOf
EN

Stack Overflow用户
提问于 2017-10-03 03:00:41
回答 1查看 92关注 0票数 1

我对泛型有编译问题。当我使用asInstanceOf时,代码编译得很好。我想摆脱asInstanceOf

我看到了一些与asInstanceOf的使用有关的其他问题,但我没有帮助我。

代码语言:javascript
复制
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]]
  }

当我从asInstanceOf中删除tempPool.asInstanceOf[F[R]]时,我会得到以下错误

代码语言:javascript
复制
[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

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-03 03:16:33

F[A]ListBuffer[A]之间没有任何关系,只有∀A∃B F[A] <: ListBuffer[B]。这一点很重要:

代码语言:javascript
复制
type ConstLBInt[A] = ListBuffer[Int]
val x: RoundRobin[Resource, ConstLBInt] = ??? // Legal
// Tries to manipulate ListBuffer[Int]s as if they were ListBuffer[Resources]s

将类型声明更改为

代码语言:javascript
复制
trait RoundRobin[R <: Resource, F[A] <: mutable.ListBuffer[A]]
//                                !                        !

这就强制了∀A F[A] <: ListBuffer[A],例如,overrideMutableResourceList中的updated: F[R]被称为ListBuffer[R]

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46536586

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档