I'm trying to understand how generics work with inheritance in Scala. I have the following code:
sealed trait Model {}
case class Model1() extends Model
case class Model2() extends Model
trait Repo[A <: Model] {
def doSomething(model: A)
}
class Repo1 extends Repo[Model1] {
override def doSomething(model: Model1): Unit = {
println("Model 1")
}
}
class Repo2 extends Repo[Model2] {
override def doSomething(model: Model2): Unit = {
println("Model 2")
}
}
object Play extends App {
def getModel(i: Int): Model =
i match {
case 1 => Model1()
case 2 => Model2()
case _ => throw new RuntimeException("model not found")
}
val model = getModel(1)
val repo = model match {
case _: Model1 => new Repo1
case _: Model2 => new Repo2
case _ => throw new RuntimeException("something went wrong")
}
repo.doSomething(model)
}
On the last line repo.doSomething(model)
I get Type mismatch. Required: _.$1 Found: Model
According to this answer What is the correct way to implement trait with generics in Scala? if my repos classes extend the trait with the type should work.
I'm new to Scala and I'm trying to wrap my head around the type system, generics, implicit, upper/lower bounds ...
What is _.$1
type and how can I make this work? Thanks!