JulienD JulienD - 1 month ago 5
Scala Question

Scala subtype parameter

I created a class

Project
extending a
Model
:

abstract class Model
case class Project(...) extends Model


and an object
Table
extending
Base
:

abstract class Base {
val tableForm: Form[Model]
}

object Table extends Base {
val tableForm: Form[Project] = (...)
}


Why is it that it won't compile and how can I fix it? ("overriding method/value tableForm in class Base of type => Form[Model]")

I just wanted to force all subclasses of
Base
to have a
tableForm
attribute.

Answer

Because Form[Project] is not a subclass of Form[Model]. So the compiler complains about incompatible type in overriding value.

Form[T] is invariant. You can read the variance doc

To fix this, you can add a type parameter to Base.

abstract class Base[M <: Model] {
  val tableForm: Test[M]
}

object Table extends Base[Project] {
  val tableForm: Test[Project] = ???
}