简体   繁体   English

scala - 在泛型中使用asInstanceOf

[英]scala - using asInstanceOf with Generics

I'm having compilation issues with generics. 我有泛型的编译问题。 The code compiles fine when I use asInstanceOf . 当我使用asInstanceOf时,代码编译得很好。 I want to get rid of asInstanceOf . 我想摆脱asInstanceOf

I saw some other questions related to the usage of asInstanceOf , but I didn't help me. 我看到了一些与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]]
  }

When I remove the asInstanceOf from tempPool.asInstanceOf[F[R]] I get the below error 当我从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

This issue happens also for the line original.asInstanceOf[mutable.ListBuffer[R]] 这个问题也发生在original.asInstanceOf[mutable.ListBuffer[R]]original.asInstanceOf[mutable.ListBuffer[R]]

  • What is the reason for this issue? 这个问题的原因是什么?
  • How can I avoid using asInstanceOf ? 如何避免使用asInstanceOf

Thanks 谢谢

There's no relationship between F[A] and ListBuffer[A] , only that ∀A∃BF[A] <: ListBuffer[B] . F[A]ListBuffer[A]之间没有关系,只有∀A∃BF[A] <: ListBuffer[B] This is important: 这个很重要:

type ConstLBInt[A] = ListBuffer[Int]
val x: RoundRobin[Resource, ConstLBInt] = ??? // Legal
// Tries to manipulate ListBuffer[Int]s as if they were ListBuffer[Resources]s

Change the declaration of your type to 将类型声明更改为

trait RoundRobin[R <: Resource, F[A] <: mutable.ListBuffer[A]]
//                                !                        !

This forces ∀AF[A] <: ListBuffer[A] , so that eg the updated: F[R] in overrideMutableResourceList is known to be a ListBuffer[R] . 这迫使∀AF[A] <: ListBuffer[A] ,因此例如overrideMutableResourceListupdated: F[R]已知为ListBuffer[R]

There are probably other parts of the class that will be simplified by this. 这个类可能会被简化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM