Scala 协变类型 T 出现在不变的位置

Scala covariant type T occurs in invariant position

我有这个特质:

trait Delivery[T] {
  def form(): Form[T]
}

其中 Form 来自 play2 框架。

然后我有实现交付特征的对象:

case class NewPostValidator(town: String, number: Int)

object NewPost extends Delivery[NewPostValidator]{
  def form(): Form[NewPostValidator] = Form(mapping(
    "town" -> nonEmptyText,
    "number" -> number)(NewPostValidator.apply)(NewPostValidator.unapply))
}

现在我想编写接受实现特征传递的对象列表的函数。而且我不能为它的参数写类型。如果我试着这样写

list: List[Delivery[AnyRef]]

我遇到了类型不匹配错误,如果我将 Delivery trait 更改为:

trait Delivery[+T] {
    def form(): Form[T]
}

我有 Scala 协变类型 T 发生在不变位置错误。 如何描述此参数的类型?

我不确定您是否希望方法中的所有表单都具有相同的基础类型,或者您是否关心 Form 中的 return 类型。了解这里发生的事情会很好。

trait Delivery[T] {
  def form(): Form[T]
}

case class NewPostValidator(town: String, number: Int)

object NewPost extends Delivery[NewPostValidator]{
  def form(): Form[NewPostValidator] = Form(mapping(
    "town" -> nonEmptyText,
    "number" -> number)(NewPostValidator.apply)(NewPostValidator.unapply))

  def accept[T <: Delivery[_]](list: List[T]): List[Form[_]] = {
    list.map(_.form())
  }

}