Scala dynamic type

452 views Asked by At
object BugFixProject {

  def main (args: Array[String]) {
    val repoWithEntities = Seq(
      (ARepo, Seq(A("", ""), A("", ""))),
      (BRepo, Seq(B("", ""), B("", "")))
    )

    printall(repoWithEntities)
  }

  def printall[Entity](pairs: Seq[(BaseRepo[Entity], Seq[Entity])]) : Seq[String] = {
    pairs.map { t =>
      val repo = t._1
      val entities = t._2

      entities.map(repo.toString(_))
    }.flatten
  }

}

case class A(foo: String, bar: String){}
case class B(foo: String, bar: String){}

trait BaseRepo[X] {
  def toString(x: X) : String = x.toString
}

object BRepo extends BaseRepo[B] {}
object ARepo extends BaseRepo[A] {}

printall should be used like stated in the main method. But then I get the following error during compilation:

Error:(12, 9) no type parameters for method printall: (pairs: Seq[(BaseRepo[Entity], Seq[Entity])])Seq[String] exist so that it can be applied to arguments (Seq[(BaseRepo[_ >: B with A <: Product with Serializable], Seq[Product with Serializable])])
 --- because ---
argument expression's type is not compatible with formal parameter type;
 found   : Seq[(BaseRepo[_ >: B with A <: Product with Serializable], Seq[Product with Serializable])]
 required: Seq[(BaseRepo[?Entity], Seq[?Entity])]
        printall(repoWithEntities)
        ^

And

Error:(12, 18) type mismatch;
 found   : Seq[(BaseRepo[_ >: B with A <: Product with Serializable], Seq[Product with Serializable])]
 required: Seq[(BaseRepo[Entity], Seq[Entity])]
        printall(repoWithEntities)
                 ^

I do not understand the error messages. Is it maybe possible that in

def printall[Entity]

Entity can only be 1 specific type?

1

There are 1 answers

1
Puneeth Reddy V On

Try making your function call in a very generic way as shown below

  def printall(pairs: Seq[(BaseRepo[_], Seq[_])]) : Seq[String] = {

This way you will be able to call printall method with either BRepo or ARepo object.