tharindu_DG tharindu_DG - 5 months ago 99
Scala Question

scala - using asInstanceOf with Generics

I'm having compilation issues with generics. The code compiles fine when I use

. I want to get rid of

I saw some other questions related to the usage of
, but I didn't help me.

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)


When I remove the
I get the below error

[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

  • What is the reason for this issue?

  • How can I avoid using


Answer Source

There's no relationship between F[A] and ListBuffer[A], only that ∀A∃B F[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 ∀A F[A] <: ListBuffer[A], so that e.g. the updated: F[R] in overrideMutableResourceList is known to be a ListBuffer[R].

There are probably other parts of the class that will be simplified by this.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download