2017-10-03 7 views
1

제네릭과 관련된 컴파일 문제가 있습니다. asInstanceOf을 사용할 때 코드가 잘 컴파일됩니다. 나는 asInstanceOf를 제거하고 싶다.스칼라 - 제네릭과 함께 asInstanceOf 사용

asInstanceOf의 사용과 관련된 몇 가지 다른 질문을 보았지만 도움이되지 않았습니다. 내가 tempPool.asInstanceOf[F[R]]에서 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]] 
    } 

나는 아래의 오류

[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을 어떻게 피할 수 있습니까?

감사

답변

3

F[A]하고, 해당 ∀A∃B F[A] <: ListBuffer[B]ListBuffer[A] 사이에 관계가 없습니다. ,

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] <: ListBuffer[A]을 강제로 타입의 선언이 예를 들어, 그래서이 중요하다 overrideMutableResourceList에있는 updated: F[R]ListBuffer[R]으로 알려져 있습니다.

아마도 이것으로 단순화 될 클래스의 다른 부분이있을 것입니다.