Slick DBIO sequence failing to compile

2019-08-22 22:04发布

问题:

I am trying to save model ProductCategory object in database. While saving it,categoriesId is a Seq.

case class ProductCategory(productItemId: ProductItemId, categoryies: CategoryId, filterName: FilterName)

/*Inside another object starts*/
def saveCategoriesId(productItemId: ProductItemId, categoryId: Seq[CategoryId], filterName: FilterName):
      Future[Seq[ProductItemId]] =
        db.run({
          DBIO.sequence(categoryId.map(id => save(ProductCategory(productItemId, id, filterName))))
        })

def save(productCategory: ProductCategory): DBIO[ProductItemId] = 
      query returning query.map(_.productItemId) += productCategory

Getting following error:

[error] /Users/vish/Work/jd/app/service/ProductCategoryService.scala:20:35: type mismatch;
[error]  found   : Seq[slick.dbio.DBIOAction[models.ProductItemId,slick.dbio.NoStream,Nothing]]
[error]  required: Seq[slick.dbio.DBIOAction[models.ProductItemId,slick.dbio.NoStream,E]]
[error]       DBIO.sequence(categoryId.map(id => save(ProductCategory(productItemId, id, filterName))))

Playframework version is 2.6. This question is not duplicate of this.This issue has blocked the further development. While answering please comment if it correct way of saving categoriesId

回答1:

Normally in Scala compile error found: Nothing, required: E means that compiler couldn't infer some types. Try to specify some type parameters manually

db.run({
  DBIO.sequence[ProductItemId, Seq, All](categoryId.map(id => save(ProductCategory(productItemId, id, filterName))))
})

or

db.run({
  DBIO.sequence(categoryId.map[DBIO[ProductItemId], Seq[DBIO[ProductItemId]]](id => save(ProductCategory(productItemId, id, filterName))))
})

or introduce a local variable (then compiler will be able to infer types itself)

val actions = categoryId.map(id => save(ProductCategory(productItemId, id, filterName)))
db.run({
  DBIO.sequence(actions)
})